SVG为PDF。如何?
问题描述:
我想输出一个PDF格式的SVG文件。我尝试了一些方法,但我一直遇到问题。SVG为PDF。如何?
我用这个源作为参考: Convert SVG to PDF 和尝试以下操作:
// 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();
我碰到了几个ClassNotFoundExceptions,大多与batik.DOM,这真的很奇怪,因为我可以看到它上市在外部库中。
接下来,我尝试使用iTextG。我遵循SvgToPdf中的代码:https://developers.itextpdf.com/examples/itext-action-second-edition/chapter-15
但是后来我卡住了,因为iTextG没有PdfGraphics2D,并且该方法需要它。
任何想法,我该如何去做这件事?
答
这是我最终选择的解决方案,它依赖任何库。
WebKit引擎可以渲染SVG,这样你就可以在SVG加载到的WebView:
webView.loadUrl(Uri.fromFile(svgFile).toString());
的WebView还具有打印的功能,这样,那么你可以继续:
// 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());