Search code examples
itextpdfhtml

itext pdfHtml: set margins


I am using HTMLConverter to convert html to PDF and trying to set some margins.

Existing code:

    ConverterProperties props = new ConverterProperties();
    props.setBaseUri("src/main/resources/xslt");

    PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(dest)));
    pdf.setDefaultPageSize(new PageSize(612F, 792F));

    HtmlConverter.convertToPdf( html, pdf,    props);

Can someone please advice on how to add margins? I used Document class to setMargin but not sure how does that make into the HTMLConverter's convertToPdf method.


Solution

  • Isn't it possible for you to use HtmlConverter#convertToElements method? It returns List<IElement> as a result and then you can add its elements to a document with set margins:

     Document document = new Document(pdfDocument);
     List<IElement> list = HtmlConverter.convertToElements(new FileInputStream(htmlSource));
     for (IElement element : list) {
         if (element instanceof IBlockElement) {
                document.add((IBlockElement) element);
         }
     }
    

    Another approach: just introduce the @page rule in your html which sets the margins you need, for example:

    @page {
        margin: 0;
    }
    

    Yet another solution: implement your own custom tag worker for <html> tag and set margins on its level. For example, to set zero margins one could create tag the next worker:

    public class CustomTagWorkerFactory extends DefaultTagWorkerFactory {
         public ITagWorker getCustomTagWorker(IElementNode tag, ProcessorContext context) {
             if (TagConstants.HTML.equals(tag.name())) {
                 return new ZeroMarginHtmlTagWorker(tag, context);
             }
             return null;
         }
    }
    
    
    
    public class ZeroMarginHtmlTagWorker extends HtmlTagWorker {
         public ZeroMarginHtmlTagWorker(IElementNode element, ProcessorContext context) {
             super(element, context);
             Document doc = (Document) getElementResult();
             doc.setMargins(0, 0, 0, 0);
         }
    }
    

    and pass it as a ConverterProperties parameter to Htmlconverter:

    converterProperties.setTagWorkerFactory(new CustomTagWorkerFactory());
    HtmlConverter.convertToPdf(new File(htmlPath), new File(pdfPath), converterProperties);