2

I'm trying to output an SVG file into a PDF. I've tried a few approaches, but I keep running into problems.

I used this source as reference: Convert SVG to PDF and tried the following:

// Save this SVG into a file (required by SVG -> PDF transformation process)
File svgFile = File.createTempFile("graphic-", ".svg");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMSource source2 = new DOMSource(svgXmlDoc);
FileOutputStream fOut = new FileOutputStream(svgFile);
try { transformer.transform(source2, new StreamResult(fOut)); }
finally { fOut.close(); }

// Convert the SVG into PDF
File outputFile = File.createTempFile("result-", ".pdf");
SVGConverter converter = new SVGConverter();
converter.setDestinationType(DestinationType.PDF);
converter.setSources(new String[] { svgFile.toString() });
converter.setDst(outputFile);
converter.execute();

I ran into several ClassNotFoundExceptions, mostly related to batik.DOM, which is really strange, since I can see it listed in the external libraries.

Next, I tried using iTextG. I followed the code in SvgToPdf: https://developers.itextpdf.com/examples/itext-action-second-edition/chapter-15

But then I get stuck, as iTextG does not have PdfGraphics2D, and that method requires it.

Any idea on how can I go about this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kartik Prabhu
  • 411
  • 1
  • 4
  • 16

1 Answers1

2

Here's the solution I ended up going with, which does rely on any libraries.

The WebKit engine can render an SVG, so you can load an SVG into a WebView:

webView.loadUrl(Uri.fromFile(svgFile).toString());

WebView also has the ability to print, so then you can continue with:

// Get a PrintManager instance
PrintManager printManager = (PrintManager) getActivity()
        .getSystemService(Context.PRINT_SERVICE);

// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();

// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
PrintJob printJob = printManager.print(jobName, printAdapter,
        new PrintAttributes.Builder().build());
Kartik Prabhu
  • 411
  • 1
  • 4
  • 16