You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Apache FOP和Java生成PDF:替换FileOutputStream为ByteArrayOutputStream

Convert Apache FOP PDF Output to ByteArrayOutputStream & Base64

Got it! Here's exactly how you can adjust your Apache FOP + Java code to swap out FileOutputStream for ByteArrayOutputStream, then encode the resulting PDF to a Base64 string:

Modified Full Code Example

import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringReader;
import java.util.Base64;

public class PdfGenerator {
    // Overloaded method for XML string input (instead of file)
    public String generatePdfFromXmlStringAsBase64(String xmlContent, String xslFoPath) throws Exception {
        FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        try {
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer xslfoTransformer = transformerFactory.newTransformer(new StreamSource(new File(xslFoPath)));

            // Use StringReader for in-memory XML content
            xslfoTransformer.transform(new StreamSource(new StringReader(xmlContent)), new SAXResult(fop.getDefaultHandler()));

            return Base64.getEncoder().encodeToString(outStream.toByteArray());
        } finally {
            outStream.close(); // No-op for ByteArrayOutputStream, but follows best practices
        }
    }

    // Updated method for file-based XML input
    public String generatePdfFromFilesAsBase64(String xmlInputPath, String xslFoPath) throws Exception {
        FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        try {
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer xslfoTransformer = transformerFactory.newTransformer(new StreamSource(new File(xslFoPath)));

            xslfoTransformer.transform(new StreamSource(new File(xmlInputPath)), new SAXResult(fop.getDefaultHandler()));

            return Base64.getEncoder().encodeToString(outStream.toByteArray());
        } finally {
            outStream.close();
        }
    }
}

Key Changes Explained

  • Swap output stream type: Replace FileOutputStream with ByteArrayOutputStream outStream = new ByteArrayOutputStream(); to hold the PDF content in memory instead of writing to a local file.
  • Pass memory stream to FOP: When initializing your Fop instance, pass the ByteArrayOutputStream — FOP will render the PDF directly into this in-memory stream.
  • Encode to Base64: After the transformation finishes, use Base64.getEncoder().encodeToString(outStream.toByteArray()) to convert the raw PDF bytes into a Base64 string for your downstream use case.
  • Resource handling: Even though ByteArrayOutputStream's close() method doesn't release resources, including it in a finally block adheres to standard resource management practices.

Quick Notes

  • If your XML or XSL-FO content exists as strings (not files), use StreamSource(new StringReader(yourContent)) instead of file-based sources — I included an overloaded method for this scenario.
  • Ensure all required Apache FOP dependencies (fop, xml-apis, xalan, etc.) are present in your project to avoid runtime errors.

内容的提问来源于stack exchange,提问作者Karthikeyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:44:07