Batik SVG to PDF - PDFTranscoder - Page Size A4

2.8k views Asked by At

I was succesful converting an SVG File into PDF using Apache Batik.

The following code is used to generate PDF:

import org.apache.fop.svg.PDFTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
...

File svgFile = new File("./target/test.svg");
...

PDFTranscoder transcoder = new PDFTranscoder();
try (FileInputStream fileInputStream = new FileInputStream(svgFile); FileOutputStream fileOutputStream = new FileOutputStream(new File("./target/test-batik.pdf"))) {
    TranscoderInput transcoderInput = new TranscoderInput(fileInputStream);
    TranscoderOutput transcoderOutput = new TranscoderOutput(fileOutputStream);
    transcoder.transcode(transcoderInput, transcoderOutput);
}

Now I want to influence the page size of the resulting PDF so I get a page size for A4. How could I do that?

I have tried some key hints but with no effect.

2

There are 2 answers

0
Bob Schultz On BEST ANSWER

I've recently had this same problem. This might not exactly solve your issue, but I was at least able to produce a PDF with the correct aspect ratio for a page (U.S. letter size in this case) with the following Groovy (almost Java) code:

...

TranscoderInput transcoderInput = new TranscoderInput(fileInputStream)
TranscoderOutput transcoderOutput = new TranscoderOutput(fileOutputStream)
PDFTranscoder transcoder = new PDFTranscoder()
int dpi = 100
transcoder.addTranscodingHint(PDFTranscoder.KEY_WIDTH, dpi * 8.5 as Float)
transcoder.addTranscodingHint(PDFTranscoder.KEY_HEIGHT, dpi * 11 as Float)
transcoder.transcode(transcoderInput, transcoderOutput)

Hope this helps.

0
oerni74 On

You can compute the values for the PDFTranscoder transcodinghints. So A4 is 210mm x 297 mm. The PDF.Transcoder.KEY_PIXEL_TO_MILLIMETER has a default of 0.264583 (See Documentation).

Now compute the values for:

  • KEY_WIDTH: 210/0.264583=793.7
  • KEY_HEIGHT: 297/0.264583=1122.52

So the code to get the A4 document will look like this:

PDFTranscoder t = new PDFTranscoder();
t.addTranscodingHint(PDFTranscoder.KEY_HEIGHT, (float)1122.52);
t.addTranscodingHint(PDFTranscoder.KEY_WIDTH, (float)793.70);

You can inspect the size in Adobe Reader and see that the document size will be 210x297mm = A4.