android - SVG 到 PDF。如何?

标签 android svg itext batik itextg

我正在尝试将 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());

关于android - SVG 到 PDF。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46803470/

相关文章:

java - onItemClick 单击时不起作用

android - Android 中 HashMap 的内存效率

javascript - SVG 路径元素 .transition() - 添加到哪里?

SVG 变换原点在 Inkscape 中被破坏

iTextSharp - 将新文档创建为 Byte[]

java - 如何设置PDF存储的默认路径

java - 在另一个 Activity 中打开 TextView 链接 - 自定义 ClickableSpan

Android:如何检测手机何时处于 Activity 状态和空闲状态?

javascript - 将 SVG 字符串转换为 base64