8

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.

Walter
  • 225
  • 4
  • 13

2 Answers2

1

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.

Bob Schultz
  • 136
  • 1
  • 6
0

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.

BuZZ-dEE
  • 3,875
  • 7
  • 48
  • 76
oerni74
  • 1
  • 3