We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

How to do page break while converting HTML to PDF

Hi,

We are having dynamic html and in html we are passing page break like below

<div style="page-break-after: always">Casey</div>

but when we convert into pdf page break is not coming ,

so can you please suggest what is best way to do page break while converting html to pdf , or if we have any other way please suggest us .

@caseyfriese,

We have tested your scenario with the latest version 17.11 of Aspose.Pdf for .NET API and works fine. Please refer to these input and output documents: Files.zip (24.4 KB)

[C#]

string dataDir = @"C:\Pdf\test492\";
Document document = new Document(dataDir + "input.html", new HtmlLoadOptions());
document.Save(dataDir + "output.pdf", SaveFormat.Pdf);

Hey, can you please reupload these files as public please? I have a similar problem and this zip might help.

@saulosag

Please use following link to download files. Also, in case you face any issue or have any other query, please feel free to create a new topic. We will surely assist you accordingly.

https://www.dropbox.com/s/t02r197zmxtp1ls/Files.zip?dl=0

Hey. My problem is, using page-break-after: always it messes up the header added in the document (via builder, not in the html).

<html>
	<head>
	</head>
	<body>
		<div style="page-break-after: always">Page 1</div>
		<div>Page 2</div>
	</body>
</html>

In this example, the first page won’t have a header. Note the header-inserting code below:

builder.PageSetup.HeaderDistance = 10;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
byte[] imgBytes = GetHeaderImage();
Shape img = builder.InsertImage(imgBytes);
img.Width = 565;
builder.InsertBreak(BreakType.ParagraphBreak);

@saulosag

It seems like you are using Aspose.Words API. We request you to please share complete code snippet which you are using in your environment. We will test the scenario in our environment and address it accordingly.

public class PdfSection
{
	public virtual Aspose.Pdf.Document ToPdfDocument()
	{
		Document wordDocument = new Document();
		DocumentBuilder builder = new DocumentBuilder(wordDocument);
		SetStyles(builder);
		string html = RenderHtml();
		builder.InsertHtml(html);
		SetHeader(builder);
		SetFooter(builder);


		// prevent line breaking inside table rows
		Node[] tableNodes = wordDocument.GetChildNodes(NodeType.Table, true).ToArray();
		
		foreach (var node in tableNodes)
		{
			var nodeAsTable = (Table)node;
			
			foreach(Row row in nodeAsTable.Rows)
			{
				if (row.RowFormat.HeadingFormat)
				{
					row.RowFormat.HeadingFormat = false;
					foreach(Cell cell in row.Cells)
					{
						cell.EnsureMinimum();
						foreach(Paragraph para in cell.Paragraphs)
						{
							if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
								para.ParagraphFormat.KeepWithNext = true;
						}
					}
				}

				row.RowFormat.AllowBreakAcrossPages = false;
			}
		}

		wordDocument.UpdateFields();
		MemoryStream pdfStream = new MemoryStream();
		wordDocument.Save(pdfStream, SaveFormat.Pdf);

		return new Aspose.Pdf.Document(pdfStream);
	}

	protected virtual void SetStyles(DocumentBuilder builder)
	{
		builder.PageSetup.PageStartingNumber = 1;
		builder.PageSetup.Orientation = Orientation.Portrait;
		builder.PageSetup.PaperSize = PaperSize.A4;
		builder.PageSetup.LeftMargin = 20;
		builder.PageSetup.RightMargin = 8;
		builder.PageSetup.TopMargin = 28.34;
		builder.PageSetup.BottomMargin = 42.52;
	}

	public virtual string RenderHtml()
	{
		if (ViewName != null && Model != null)
			return RenderHtmlWithRazor();
		else if (ChildSections.Any())
			return RenderHtmlWithChilds();
		else
			throw new Exception("Wrong usage");
	}

	private string RenderHtmlWithRazor()            
	{
		string rawView = LoadView(ViewName);
		string html = Razor.Parse(rawView, Model);
		return html; 
	}

	private string LoadView(string viewName)
	{
		
		string path = Path.Combine(Assembly.GetExecutingAssembly().CodeBase, "..", ViewsPath, viewName + ".cshtml");
		string viewText = File.ReadAllText(path.Replace("file:///", ""));
		return viewText;
	}

	private string RenderHtmlWithChilds()
	{
		StringBuilder builder = new StringBuilder();
		ChildSections.ForEach(cs =>
		{
			builder.Append(cs.RenderHtml().Replace("\\n","<br>"));
		});
		return builder.ToString();
	}

	private void SetHeader(DocumentBuilder builder)
	{
		builder.PageSetup.HeaderDistance = 10;
		builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
		byte[] imgBytes = GetHeaderImage();
		Shape img = builder.InsertImage(imgBytes);
		img.Width = 565;
		builder.InsertBreak(BreakType.ParagraphBreak);
	}

	private byte[] GetHeaderImage()
	{
		string uriImage = Path.Combine(Assembly.GetExecutingAssembly().CodeBase, "..", ImgPath, "header.png");
		string imagePath = new Uri(uriImage).LocalPath;
		var header = new HeaderImage(imagePath);
		var imgBytes = header.Bytes();
		return imgBytes;
	}

	private void SetFooter(DocumentBuilder builder)
	{
		builder.PageSetup.FooterDistance = 8;
		builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
		Table footerTable = builder.StartTable();
		Cell cell = builder.InsertCell();
		cell.CellFormat.Shading.BackgroundPatternColor = System.Drawing.Color.White;
		builder.Font.Color = System.Drawing.Color.Black;
		builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
		builder.Font.Size = 8;
		var year = Convert.ToInt32(ReportYearAsString);
		var month = Convert.ToInt32(ReportMonthAsString);
		var date = new DateTime(ano, mes, 1);
		builder.Write($"REPORT FROM {date.ToString("MMMM").ToUpper()}/{ReportYearAsString}");

		Cell pageCell = builder.InsertCell();
		pageCell.CellFormat.Shading.BackgroundPatternColor = System.Drawing.Color.White;
		builder.Font.Color = System.Drawing.Color.Black;
		builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
		builder.Font.Size = 8;
		builder.InsertField("PAGE", "");

		builder.EndRow();
		footerTable.ClearBorders();
		footerTable.PreferredWidth = PreferredWidth.FromPercent(100);
		footerTable.SetBorder(BorderType.Top, LineStyle.Single, 2, System.Drawing.Color.Black, true);
		builder.EndTable();
	}
}

@saulosag

Thanks for sharing the code snippet. In your code, you are saving document to PDF and returning it as Aspose.Pdf.Document. It should be Aspose.Words.Document.

To ensure a timely and accurate response, please attach the following resources here for testing:

  • Your input Word document.
  • Please attach the output Word/PDF file that shows the undesired behavior.
  • Please attach the expected output Word/PDF file that shows the desired behavior.
  • Please create a standalone console application (source code without compilation errors) that helps us to reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.