Search code examples
javapdfsvgpdfboxbatik

Apache Batik SVG to PDF - Output PDF is Incorrect Size


I'm trying to convert an SVG file into a PDF for embedding into another PDF document. I'm using the batik transcoder, passing in the bytes for the SVG and getting the data for the PDF back.

My main PDF document and the SVG file passed into the transcoder both have dimensions of:

width="602.8" height="763.8"

The output PDF file generated from the SVG is smaller however. Because of this, when embedded into our main document, the generated SVG PDF doesn't take up all available space in our main PDF as I would expect it to because it has smaller dimensions. How can I force the output pdf to have the same dimensions of the main document / input SVG.


Solution

  • So after some further research I came to a solution. We're using PDFBox as our pdf manipulation tool which uses a DPI of 72 by default for documents.

    Batik on the other hand uses a DPI of 96 when transcoding an SVG to a PDF file. This makes the output file slightly smaller than the main PDFBox generated document. To switch Batik to a DPI that supports PDFBox by default we must change the pixel to mm conversion from 96dpi to 72dpi.

    We can add a transcoding hint to our PDFTranscoder as follows:

    transcoder.addTranscodingHint(PDFTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER,
    (25.4f / 72f));
    

    where (25.4f / 72f) is equal to 72dpi. This will replace the default dpi of 96dpi (25.4f / 96f)