我正在尝试将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,而且该方法需要它。
关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
这是我最终使用的解决方案,它依赖于任何库。
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());