Skip to content

966259: Added proper code sample for two phase PDF margin customization. #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36221.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeaderAndFooterForSpecificPage", "HeaderAndFooterForSpecificPage\HeaderAndFooterForSpecificPage.csproj", "{546D19CF-BDDF-423D-A165-007E02911EF9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{546D19CF-BDDF-423D-A165-007E02911EF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{546D19CF-BDDF-423D-A165-007E02911EF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{546D19CF-BDDF-423D-A165-007E02911EF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{546D19CF-BDDF-423D-A165-007E02911EF9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E1A1C446-BB6A-4714-BE88-CC30C480A0A5}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
}
.page-break {
page-break-after: always;
}
.chapter {
margin-bottom: 30px;
}
h1 {
color: #2c3e50;
font-size: 24px;
margin-top: 40px;
}
h2 {
color: #3498db;
font-size: 20px;
margin-top: 30px;
}
p {
margin-bottom: 15px;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
img {
max-width: 100%;
height: auto;
margin: 10px 0;
}
</style>
</head>
<body>

<div class="chapter">
<h1>Chapter 1: Introduction to PDF Generation</h1>
<p>This document demonstrates how to create multi-page PDF content using HTML. The content is structured to span exactly 5-6 pages when converted to PDF.</p>

<h2>1.1 Document Structure</h2>
<p>Proper document structure is essential for consistent PDF conversion. We use:</p>
<ul>
<li>Semantic HTML5 elements</li>
<li>CSS for styling and layout</li>
<li>Page break controls where needed</li>
</ul>

<h2>1.2 Page Layout Considerations</h2>
<p>When designing for PDF output, consider:</p>
<table>
<tr>
<th>Element</th>
<th>Consideration</th>
</tr>
<tr>
<td>Images</td>
<td>Use high resolution (300dpi) for print quality</td>
</tr>
<tr>
<td>Tables</td>
<td>Avoid row breaks across pages when possible</td>
</tr>
<tr>
<td>Text</td>
<td>Maintain readable font sizes (10-12pt)</td>
</tr>
</table>
</div>

<div class="page-break"></div>

<div class="chapter">
<h1>Chapter 2: Advanced PDF Features</h1>

<h2>2.1 Headers and Footers</h2>
<p>Headers and footers should be consistent across pages but may need to be suppressed on title pages.</p>

<h2>2.2 Page Numbering</h2>
<p>Page numbers are typically added during PDF generation rather than in the HTML.</p>

<h2>2.3 Multi-column Layout</h2>
<p>CSS columns can be used for newspaper-style layouts:</p>
<div style="column-count: 2; column-gap: 20px; margin: 20px 0;">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula. Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor.</p>
<p>Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere.</p>
<p>Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet.</p>
</div>
</div>

<div class="page-break"></div>

<div class="chapter">
<h1>Chapter 3: Visual Elements in PDF</h1>

<h2>3.1 Images</h2>
<p>Properly sized images help maintain document flow:</p>
<img src="https://via.placeholder.com/600x200" alt="Sample Image" style="display: block; margin: 0 auto;">

<h2>3.2 Charts and Graphs</h2>
<p>For data visualization, consider using SVG or high-resolution PNG images:</p>
<img src="https://via.placeholder.com/600x300" alt="Sample Chart">

<h2>3.3 Borders and Backgrounds</h2>
<div style="background-color: #f8f9fa; border: 1px solid #dee2e6; padding: 15px; margin: 20px 0;">
<p>Styled divs can highlight important content while maintaining print readability.</p>
</div>
</div>

<div class="page-break"></div>

<div class="chapter">
<h1>Chapter 4: Long-form Content</h1>

<h2>4.1 Multi-page Tables</h2>
<p>Tables that span multiple pages should have headers repeated:</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<!-- Repeat this block to extend content -->
<tr><td>1</td><td>Item A</td><td>Description of item A</td><td>$100</td></tr>
<tr><td>2</td><td>Item B</td><td>Description of item B</td><td>$200</td></tr>
<tr><td>3</td><td>Item C</td><td>Description of item C</td><td>$300</td></tr>
<!-- Repeat 15-20 times to ensure multi-page content -->
</tbody>
</table>
</div>

<div class="chapter">
<h1>Chapter 5: Conclusion</h1>
<p>This template demonstrates how to structure HTML content that will reliably convert to a 5-6 page PDF document. Key takeaways:</p>

<ul>
<li>Use proper semantic structure</li>
<li>Control page breaks with CSS</li>
<li>Optimize images for print</li>
<li>Test with your PDF converter</li>
</ul>

<h2>5.1 Final Notes</h2>
<p>Always test your HTML-to-PDF conversion with actual content to ensure proper pagination. The exact page count may vary slightly based on:</p>
<ul>
<li>PDF converter settings</li>
<li>Font rendering differences</li>
<li>Margin requirements</li>
</ul>
</div>

</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>HeaderAndFooterForSpecificPage</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Syncfusion.HtmlToPdfConverter.Net.Windows" Version="*" />
</ItemGroup>

<ItemGroup>
<None Update="Data\sample.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
using Syncfusion.Drawing;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;


// Initialize HTML to PDF converter
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
//Convert the HTML to PDF without margins.
BlinkConverterSettings settings = new BlinkConverterSettings();
settings.Margin.All = 0;
settings.ViewPortSize = new Size(1024, 768); // Set the viewport size for rendering
htmlConverter.ConverterSettings = settings;

// Load HTML content from a file
string html = File.ReadAllText(Path.GetFullPath(@"Data/Sample.html"));

// Convert HTML to PDF
using (PdfDocument document = htmlConverter.Convert(html, ""))
{
if (Directory.Exists("Output") == false)
{
Directory.CreateDirectory("Output");
}
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Output/Output-HTML-To-PDF.pdf"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// Save the converted PDF document
document.Save(fileStream);
}
}
htmlConverter.Close();

// Load the source
using (FileStream inputStream = new FileStream(Path.GetFullPath(@"Output/Output-HTML-To-PDF.pdf"), FileMode.Open, FileAccess.Read))
{
//Load the converted document
using (PdfLoadedDocument loadedDocument = new PdfLoadedDocument(inputStream))
{

// Define pages requiring headers
HashSet<int> pagesWithHeaders = new HashSet<int> { 0, 2 }; // 0-based: pages 1 and 3

// Create a new PDF document
using (PdfDocument finalDocument = new PdfDocument())
{
// Create a section for the new document
PdfSection section = finalDocument.Sections.Add();
// Set margins for the section
section.PageSettings.Margins.All = 0;
// Iterate over each page in the original document
for (int i = 0; i < loadedDocument.Pages.Count; i++)
{
bool hasHeaderAndFooter = pagesWithHeaders.Contains(i);
if (hasHeaderAndFooter)
{
// Set the page size to match the original document by allocating space for headers and footer.
section.PageSettings.Size = loadedDocument.Pages[i].Size;
}
else
{
// Set the page size to match the original document
section.PageSettings.Size = loadedDocument.Pages[i].Size;
}
// Create a new page in the final document
PdfPage destPage = section.Pages.Add();

// Copy content from the loaded document
PdfTemplate contentTemplate = loadedDocument.Pages[i].CreateTemplate();

if (hasHeaderAndFooter)
{
//Define the font for header
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
//Draw header and footer
AddHeaderAndFooter(destPage, "PDF Page Header Content", "PDF Page Footer Content", font);
//Draw the template
destPage.Graphics.DrawPdfTemplate(contentTemplate, new PointF(0, 50)); //50 Header height
}
else
{
// Draw the content on the destination page
destPage.Graphics.DrawPdfTemplate(contentTemplate, new PointF(0, 0));
}
}
using (FileStream fileStream1 = new FileStream(Path.GetFullPath(@"Output/Output-With-HeaderAndFooter.pdf"), FileMode.Create, FileAccess.ReadWrite))
{
// Save the converted PDF document
finalDocument.Save(fileStream1);
}
}
}
}

static void AddHeaderAndFooter(PdfPage page, string headerText, string footerText, PdfFont font)
{
// Draw header
page.Graphics.DrawLine(PdfPens.Gray, new PointF(0, 50), new PointF(page.GetClientSize().Width, 50));

//Measure the header text
SizeF textSize = font.MeasureString(headerText);
page.Graphics.DrawString(headerText, font, PdfBrushes.Red, new PointF((page.GetClientSize().Width - textSize.Width) / 2, (50 - textSize.Height) / 2));

// Draw footer
page.Graphics.DrawLine(PdfPens.Gray, new PointF(0, page.GetClientSize().Height - 50), new PointF(page.GetClientSize().Width, page.GetClientSize().Height - 50));
page.Graphics.DrawString(footerText, font, PdfBrushes.Green, new PointF(10, page.GetClientSize().Height - 50)); //50 Footer height
}
Loading