2

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.

nkare
  • 397
  • 6
  • 17

1 Answers1

5

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);
Uladzimir Asipchuk
  • 2,368
  • 1
  • 9
  • 19
  • In case of HtmlConverter.convertToPdf, where it is possible to work with css, second solution is excellent. It's possible to work for margin on every html tag, in my case I had some problem with @page, I "guess" because I'm adding an header using page events. Anyway since I have not so much time to go deep, using margin on body tag worked perfectly for me: body { ...; margin-top: 80px; ...; } – Falco Jul 25 '21 at 11:42