gpt4 book ai didi

java - 使用 Flying Saucer 将 Svg 集成到 pdf 中

转载 作者:搜寻专家 更新时间:2023-11-01 03:00:11 24 4
gpt4 key购买 nike

我遇到了将 html 转换为 pdf 的情况,幸运的是我可以通过 Flying Saucer api 实现这一点。但是我的 HTML 在转换时包含 svg 标签,我无法获得 pdf 格式的 svg。可以使用 Stackoverflow question 来实现和 Tutorial .

replacedElementFactory 是什么意思?

ChainingReplacedElementFactory chainingReplacedElementFactory 
= new ChainingReplacedElementFactory();
chainingReplacedElementFactory.addReplacedElementFactory(replacedElementFactory);
chainingReplacedElementFactory.addReplacedElementFactory(new SVGReplacedElementFactory());
renderer.getSharedContext().setReplacedElementFactory(chainingReplacedElementFactory);

最佳答案

这只是教程中的错误,不需要带有 replacedElementFactory 的行。

这是我的工作示例。

Java:

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class PdfSvg {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document inputDoc = builder.parse("svg.html");

ByteArrayOutputStream output = new ByteArrayOutputStream();

ITextRenderer renderer = new ITextRenderer();

ChainingReplacedElementFactory chainingReplacedElementFactory = new ChainingReplacedElementFactory();
chainingReplacedElementFactory.addReplacedElementFactory(new SVGReplacedElementFactory());
renderer.getSharedContext().setReplacedElementFactory(chainingReplacedElementFactory);

renderer.setDocument(inputDoc, "");;
renderer.layout();
renderer.createPDF(output);

OutputStream fos = new FileOutputStream("svg.pdf");
output.writeTo(fos);
}
}

HTML:

<html>
<head>
<style type="text/css">
svg {display: block;width:100mm;height:100mm}
</style>
</head>
<body>
<div>
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3"
fill="red" />
</svg>
</div>
</body>
</html>

ChainingReplacedElementFactorySVGReplacedElementSVGReplacedElementFactory 来自 tutorial .

关于java - 使用 Flying Saucer 将 Svg 集成到 pdf 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37056791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com