Batik SVG to PDF - PDFTranscoder - Page size A4

I have successfully converted an SVG file to PDF using Apache Batik.

The following code is used to generate the 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 affect the page size of the resulting PDF to get the page size for A4. How can i do this?

I tried some key tips, but no effect.

+6
source share
2 answers

I recently had the same issue. This may not completely solve your problem, but at least I was able to create a PDF file with the correct aspect ratio for the page (in our case, this is the US size) 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.

+1
source

You can calculate the values ​​for PDFTranscoder transcodes. Thus, A4 is 210 x 297 mm. PDF.Transcoder.KEY_PIXEL_TO_MILLIMETER has a default value of 0.264583 (see Documentation ).

Now calculate the values ​​for:

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

Thus, the code for receiving an 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 check the size in Adobe Reader and see that the size of the document will be 210x297 mm = A4.

0
source

Source: https://habr.com/ru/post/1261948/


All Articles