使用transformToFragment,通过传递XSLT和XML文档,我能够实现PDF 对于另一个请求,我有 XSL FO。我们可以使用XSL FO和XML文档来生成pdf吗? 请指教
使用transformToFragment,通过传递XSLT和XML文档,我能够实现PDF
对于另一个请求,我有 XSL FO。我们可以使用 XSL FO 和 XML 文档来生成 pdf 吗?
下面是代码
var AppModule = function AppModule() {}; AppModule.prototype.transformUBLAndInsertIntoFrame = function (UBL, XSLT) {
let ublStr = b64DecodeUnicode(UBL?.replaceAll("\r\n", ""));
let xsltStylesheet = b64DecodeUnicode(XSLT?.replaceAll("\r\n", ""));
const parser = new DOMParser();
let xmlDoc = parser.parseFromString(ublStr, "text/xml");
let resultDocument = document.implementation.createHTMLDocument("PDF Preview");
let xsltDoc = parser.parseFromString(xsltStylesheet, "application/xml");
console.log("Serialize:" + new XMLSerializer().serializeToString(xsltDoc));
let xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDoc);
resultDocument = xsltProcessor.transformToFragment(xmlDoc, resultDocument);
resultDocument = new XMLSerializer().serializeToString(resultDocument)
.replaceAll('&', '&')
.replaceAll('<', '<') .replaceAll('>','>' ) .replaceAll('"','"' ) .replaceAll(''',"'" ); return resultDocument; };
这里是将 XML 转换为 PDF 所需的所有代码
protected static byte[] format(byte[] xml, String xslTransformationName) throws PdfFormatterException
{
try(
ByteArrayInputStream is = new ByteArrayInputStream(xml);
ByteArrayOutputStream os = new ByteArrayOutputStream())
{
Fop fop = FopFactory.newInstance(new File(".").toURI()).newFop(MimeConstants.MIME_PDF, os);
StreamSource xsl = new StreamSource(
PdfFormatter.class.getResourceAsStream(XSL_FO_DIRECTORY + xslTransformationName));
var txFactory = TransformerFactory.newInstance();
txFactory.setURIResolver((href, base) -> {
return new StreamSource(PdfFormatter.class.getResourceAsStream(XSL_FO_DIRECTORY + href));
}); // Allow xsl:import from the same directory as the original XSLT.
Transformer tx = txFactory.newTransformer(xsl);
tx.setErrorListener(ERROR_LISTENER);
Result result = new SAXResult(fop.getDefaultHandler());
tx.transform(new StreamSource(is), result);
return os.toByteArray();
}
catch(IOException | FOPException | TransformerException e)
{
throw new PdfFormatterException("Error converting to PDF.", e);
}
}
private static final ErrorListener ERROR_LISTENER = new ErrorListener()
{
private static final Logger LOG = LoggerFactory.getLogger(PdfFormatter.class);
@Override
public void warning(TransformerException exception) throws TransformerException
{
LOG.warn(exception.getMessage(), exception);
}
@Override
public void fatalError(TransformerException exception) throws TransformerException
{
LOG.error(exception.getMessage(), exception);
}
@Override
public void error(TransformerException exception) throws TransformerException
{
LOG.error(exception.getMessage(), exception);
}
};