galao
galao

Reputation: 1301

Creating a PDF using iText without saving it to a temp file

code:

private String FILE = "e:/FirstPdf.pdf";

public void preparePDF() {
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, pdfFile);
            document.open();
            addTitlePage(document);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

everything works fine but what i want is to not save the pdf into a temporary folder but rather just insert it to a private File or something. I'm creating a web application that has a function to download PDF files, i just need the pdf to be inside a variable.

Upvotes: 0

Views: 13004

Answers (4)

Gagan Wamankar
Gagan Wamankar

Reputation: 1

you can use ByteArrayOutputStream to convert any image to pdf with out saving into a temp file.

public static byte[] imageToPDFConverterByteArray(byte[] sourcFileURL) {
    try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfWriter writer = new PdfWriter(byteArrayOutputStream);
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);
        ImageData data = ImageDataFactory.create(sourcFileURL);
        Image image = new Image(data);
        document.add(image);
        document.close();
        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();

    }
    return sourcFileURL;
}

Upvotes: 0

Bhushan
Bhushan

Reputation: 6181

You can use ByteArrayOutputStream, if you dont want to save the PDF. take a look at this example

Upvotes: 2

Zutty
Zutty

Reputation: 5377

You can write the document to an OutputStream instead of a file. If you want to be able to generate and download the PDF file dynamically (i.e. if it doesn;t take more than a second or so to generate), then you could create a servlet and write to HttpServletResponse.getOutputStream().

PdfWriter.getInstance(document, response.getOutputStream())

Upvotes: 0

gogognome
gogognome

Reputation: 759

PdfWriter has a static method getInstance(Document document, OutputStream os). Use a ByteArrayOutputStream to store the contents to a byte array. Later on, use this array to send the file to the user. Perhaps you need to wrap the array into a ByteArrayInputStream.

This way, you do not need to store the file on the file system.

Upvotes: 1

Related Questions