HTML to PDF (Orientation, Header/Footer support)

The problem my team is trying to solve involves the follow requirements:

  1. Convert HTML to PDF
  2. Dynamic content (source HTML is fully dynamic with no size limits)
  3. Orientation support (ability to toggle between Portrait and Landscape layouts)
  4. Header/Footer content support (ability to insert Headers/Footers with HTML or plain text)

Using Aspose.PDF 18.2, I’m able to explicitly convert HTML to PDF from a source html file (above average size). However, we need help figuring out how to add Orientation handling and Header/Footer content. Any assistance is appreciated. See code snippet below. Sample project is attached.

Environment information:

  • .NET Framework 3.5
  • ASP.NET Web Forms
  • Aspose.PDF for .NET 18.2
  • Visual Studio 2017

using Aspose.Pdf;
using System;
using System.IO;

namespace PDFTestWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

    protected void PDF_Click(object sender, EventArgs e)
    {
        var output = string.Empty;
        var outputPath = @"C:\PDFTest\";
        var outputFileName = System.Guid.NewGuid().ToString() + ".pdf";

        License license = new License();
        license.SetLicense("Aspose.Total.lic");

        HtmlLoadOptions options = new HtmlLoadOptions();

        Document document = new Document(Server.MapPath("PDFTest.html"), options);

        // Orientation?
        // Header?
        // Footer?

        // Prepare File System
        if (Directory.Exists(outputPath))
        {
            string[] files = Directory.GetFiles(outputPath);

            foreach (var file in files)
            {
                if (File.GetCreationTime(file) < DateTime.Now.AddDays(-1))
                {
                    File.Delete(file);
                }
            }
        }
        else
        {
            Directory.CreateDirectory(outputPath);
        }

        // Save
        output = outputPath + outputFileName;
        document.Save(output);

        document.Dispose();
    }
}

}

@azinger3

Thanks for contacting support.

Please use following code snippet in order to set Page Orientation, Height/Width, Margins and Header/Footer while converting HTML into PDF document.

var loadoptions = new HtmlLoadOptions();
loadoptions.PageInfo.IsLandscape = true;
loadoptions.PageInfo.Width = PageSize.A4.Height;
loadoptions.PageInfo.Height = PageSize.A4.Width;
loadoptions.PageInfo.Margin = new MarginInfo(10, 10, 10, 10);

Document doc = new Document(dataDir + "TestHtml.html", loadoptions);
var ms1 = new MemoryStream();
doc.Save(ms1, Aspose.Pdf.SaveFormat.Pdf);

foreach(Page page in doc.Pages)
{
 page.Header = new HeaderFooter();
 page.Header.Paragraphs.Add(new TextFragment("Header"));
 page.Footer = new HeaderFooter();
 page.Footer.Paragraphs.Add(new TextFragment("Footer"));
}
doc.Save(dataDir + "TestPdf_out1.pdf");

In case of any further assistance, please feel free to contact us.

I’m attempting to implement the suggestions. Getting the following message (see attachments)3-12-2018 8-37-39 AM.jpg (215.4 KB)
. Code snippet below. Any assistance is appreciated. Thanks!

var output = string.Empty;
var outputPath = @“C:\PDFTestWeb”;
var outputFileName = “PDFTestWeb” + System.Guid.NewGuid().ToString() + “.pdf”;

        License license = new License();
        license.SetLicense("Aspose.Total.lic");

        HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions();
        htmlLoadOptions.PageInfo.IsLandscape = true;
        htmlLoadOptions.PageInfo.Width = PageSize.A4.Height;
        htmlLoadOptions.PageInfo.Height = PageSize.A4.Width;
        htmlLoadOptions.PageInfo.Margin = new MarginInfo(10, 10, 10, 10);

        Document document = new Document(Server.MapPath("PDFTest.html"), htmlLoadOptions);
        MemoryStream memoryStream = new MemoryStream();

        document.Save(memoryStream, SaveFormat.Pdf);

        foreach (Page page in document.Pages)
        {
            page.Header = new HeaderFooter();
            page.Header.Paragraphs.Add(new HtmlFragment("<h1>Header</h1><br/><br/><p>header content</p>"));

            page.Footer = new HeaderFooter();
            page.Footer.Paragraphs.Add(new HtmlFragment("<h1>Footer</h1><br/><br/><p>footer content</p>"));
        }

        // Orientation?
        // Header?
        // Footer?

        // Prepare File System
        if (Directory.Exists(outputPath))
        {
            string[] files = Directory.GetFiles(outputPath);

            foreach (var file in files)
            {
                if (File.GetCreationTime(file) < DateTime.Now.AddDays(-1))
                {
                    File.Delete(file);
                }
            }
        }
        else
        {
            Directory.CreateDirectory(outputPath);
        }

        // Save
        output = outputPath + outputFileName;
        document.Save(output);

        document.Dispose();

@azinger3

Thanks for getting back to us.

We have tested the scenario in our environment with one of our sample HTML files and were unable to observe the issue which you have shared. Would you please share your sample HTML file with us (in a ZIP archive), so that we can test the scenario with your HTML file and address it accordingly.

Body.zip (88.6 KB)

here’s the HTML file.

@azinger3

Thanks for sharing the sample HTML file.

We have tested the scenario in our environment and observed that process took a lot of memory and CPU usage, and program hung up as well. We have logged this issue as PDFNET-44360 in our issue tracking system, for the sake of further investigation. Therefore, we were unable to notice the exception you were facing - could you please share the complete exception message along with StackTrace in text form. We will also log these details along with the issue, so that it can be investigated from that perspective.

We are sorry for the inconvenience.

Server Error in ‘/’ Application.

Item has already been added. Key in dictionary: ‘4088’ Key being added: ‘4088’
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Item has already been added. Key in dictionary: ‘4088’ Key being added: ‘4088’

Source Error:

Line 66: // Save
Line 67: output = outputPath + outputFileName;
Line 68: document.Save(output);
Line 69:
Line 70: document.Dispose();

Source File: C:\Projects\MyDev\PDFReportDemo\PDFReportDemo\Default.aspx.cs Line: 68

Stack Trace:

[ArgumentException: Item has already been added. Key in dictionary: ‘4088’ Key being added: ‘4088’]
System.Collections.SortedList.Add(Object key, Object value) +7511031
Aspose.Pdf.OperatorCollection.Insert(IList ) +321
Aspose.Pdf.OperatorCollection.„™(IList , ) +67
Aspose.Pdf.OperatorCollection.Insert(Int32 at, IList ops) +397
š..e(„˜ ) +641
•.„˜.Accept(Ž• ) +85
š..Convert(˜ , RectangleF ) +679
Aspose.Pdf.Page.Accept(˜ , RectangleF , Boolean , Boolean ) +193
š..Process() +6871
Aspose.Pdf.Page.‡() +125
Aspose.Pdf.Document.†’() +636
Aspose.Pdf.Document.Save(Stream output) +53
Aspose.Pdf.Document.Save(String outputFileName) +74
PDFReportDemo.Default.AsposePDF_Click(Object sender, EventArgs e) in C:\Projects\MyDev\PDFReportDemo\PDFReportDemo\Default.aspx.cs:68
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

Version Information: Microsoft .NET Framework Version:2.0.50727.8762; ASP.NET Version:2.0.50727.8762 StackTrace.jpg (313.4 KB)

StackTrace.jpg (313.4 KB)

See above for stacktrace and screenshot. Thanks!

@azinger3

Thanks for sharing requested information.

We have updated the issue details accordingly and will let you know about further updates. Please be patient and spare us little time.

We are sorry for the inconvenience.