Set Custom Margins

Customizing margins is a straightforward task with IronPDF.

Begin by setting up the rendering options and specifying the margins for the PDF content. In this example, we have defined a top margin of 40 units, a left margin of 20 units, a right margin of 20 units, and a bottom margin of 40 units. These margin values control the spacing between the content and the edges of each page within the PDF.

Utilize the PdfDocument.fromHtml method to convert an HTML file into a PDF document using IronPDF's extensive HTML-to-PDF capabilities. The rendering options, which include the customized margins, should be provided within the renderOptions object.

Once the HTML content has been successfully rendered into a PDF document, proceed to export the resulting PDF, taking full advantage of IronPDF's powerful document conversion features.

Here's an example code snippet demonstrating how to set margins:

Explanation of the code:

  1. Import IronPDF: Ensure you have included the necessary using directives to access IronPDF's features.

  2. Initialize HtmlToPdf: Create an object of HtmlToPdf to handle the HTML to PDF conversion.

  3. Configure Margins: Define a PdfPrintOptions object setting the margins for the PDF pages. The margins are important for layout and help define where content will be placed relative to the edge of the paper.

  4. Set Print Options: Assign the PdfPrintOptions (with margin specifications) to the renderer.PrintOptions.

  5. HTML Content: Define your HTML content in a string. This is what will be converted into the PDF format.

  6. Render HTML to PDF: Call RenderHtmlAsPdf on the renderer, passing in the HTML content. This method returns a PdfDocument object.

  7. Save PDF: Save the resulting PdfDocument to a file using SaveAs, providing the path where you want to store the PDF.

By following these steps, you can customize the PDF document margins and create well-formatted PDFs using IronPDF.

Dive into our GitHub example for setting custom PDF margins with IronPDF for Node.js!

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?