我想将 PDF 转换为 SVG 请建议一些能够有效地做到这一点的库/可执行文件。我已经使用 apache PDFBox 和 Batik 库编写了自己的 java 程序 -
PDDocument document = PDDocument.load( pdfFile );
DOMImplementation domImpl =
GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document svgDocument = domImpl.createDocument(svgNS, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(svgDocument);
ctx.setEmbeddedFontsOn(true);
// Ask the test to render into the SVG Graphics2D implementation.
for(int i = 0 ; i < document.getNumberOfPages() ; i++){
String svgFName = svgDir+"page"+i+".svg";
(new File(svgFName)).createNewFile();
// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx,false);
Printable page = document.getPrintable(i);
page.print(svgGenerator, document.getPageFormat(i), i);
svgGenerator.stream(svgFName);
}
此解决方案效果很好,但生成的 svg 文件的大小很大。(比 pdf 大很多倍)。我通过在文本编辑器中查看 svg 找出了问题所在。即使字符的字体属性相同,它将原始文档中的每个字符都包含在自己的块中。例如,hello 一词将显示为 6 个不同的文本块。有没有办法修复上面的代码?或者请提出另一种更有效的解决方案。
最佳答案
Inkscape 也可用于将 PDF 转换为 SVG。它实际上在这方面非常出色,尽管它生成的代码有点臃肿,但至少,它似乎没有您在程序中遇到的特定问题。我认为将它直接集成到 Java 中会很有挑战性,但是inkscape 为这个功能提供了一个方便的命令行界面,所以访问它的最简单方法可能是通过系统调用。
要使用 Inkscape 的命令行界面将 PDF 转换为 SVG,请使用:
inkscape -l out.svg in.pdf
然后您可以使用以下方法调用它:
Runtime.getRuntime().exec("inkscape -l out.svg in.pdf")
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html#exec%28java.lang.String%29
我认为 exec() 是同步的,只有在进程完成后才返回(虽然我不是 100% 确定),所以你应该能够在此之后读取“out.svg”。在任何情况下,谷歌搜索“java 系统调用”将产生更多关于如何正确执行该部分的信息。
关于pdf - 将pdf转换为svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4120567/