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

无需FileInputStream,用Java打印iText生成的PDF文档

Great question! You don't need to save your generated PDF to a file just to print it—you can handle everything entirely in memory, skipping the filesystem step altogether. Here's how to do it using a ByteArrayOutputStream to capture the PDF content from iText, then converting that to a ByteArrayInputStream for the printing API:

Step-by-Step Explanation

  1. Capture PDF in Memory: Instead of writing the PDF to a file with FileOutputStream, use a ByteArrayOutputStream to store the generated PDF content directly in memory.
  2. Convert to Input Stream: Turn the ByteArrayOutputStream into a ByteArrayInputStream—this gives you the InputStream the printing API needs without reading from a local file.
  3. Set Up and Submit Print Job: Use the standard Java Print Service API with your in-memory input stream to print the PDF.

Full Code Example

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import javax.print.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class InMemoryPdfPrinter {
    public static void main(String[] args) throws DocumentException, IOException, PrintException {
        // 1. Generate your PDF directly into memory
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        Document document = new Document();
        PdfWriter.getInstance(document, pdfOutputStream);

        document.open();

        // Add your existing table and data here (example table included)
        PdfPTable housingTable = new PdfPTable(3);
        housingTable.addCell(new PdfPCell(new Phrase("Property ID")));
        housingTable.addCell(new PdfPCell(new Phrase("Address")));
        housingTable.addCell(new PdfPCell(new Phrase("Status")));
        housingTable.addCell("H-001");
        housingTable.addCell("123 Main St");
        housingTable.addCell("Occupied");
        housingTable.addCell("H-002");
        housingTable.addCell("456 Oak Ave");
        housingTable.addCell("Vacant");

        document.add(housingTable);
        document.close();

        // 2. Convert the in-memory PDF to an InputStream
        ByteArrayInputStream pdfInputStream = new ByteArrayInputStream(pdfOutputStream.toByteArray());

        // 3. Configure and submit the print job
        DocFlavor printFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintService[] availablePrinters = PrintServiceLookup.lookupPrintServices(printFlavor, null);

        if (availablePrinters.length == 0) {
            System.err.println("No printers detected on the system.");
            return;
        }

        // Use the first available printer (you can let users select one if needed)
        PrintService selectedPrinter = availablePrinters[0];
        Doc printDoc = new SimpleDoc(pdfInputStream, printFlavor, null);
        DocPrintJob printJob = selectedPrinter.createPrintJob();

        printJob.print(printDoc, null);
        System.out.println("Print job sent to " + selectedPrinter.getName());
    }
}

Key Notes

  • No File I/O: This approach avoids writing the PDF to disk and reading it back, which is faster and cleaner for temporary documents.
  • Memory Considerations: If your PDF is extremely large, keep an eye on memory usage—but for most standard reports (like your housing report), this won't be an issue.
  • Printer Selection: The example uses the first available printer, but you can extend it to let users choose from the list of availablePrinters if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:40:46