0

I have a function which is generating PDF file using iText libary. My idea is that convert document to byte array but I always get a error: com.itextpdf.text.Document@2805d0d4. The file cannot be found.

Here is my PDF generation function:

    @Override
    public Boolean createdPDF() throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("iTextHelloWorld.pdf"));

        document.open();
        Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
        Chunk chunk = new Chunk("Hello World", font);

        document.add(chunk);
        document.close();
        getByteArrayFromFile(document);

        return true;
    }

Here is my convert byte array from file function:

    private byte[] getByteArrayFromFile(Document handledDocument) throws IOException {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         InputStream in = new FileInputStream(String.valueOf(handledDocument));
         byte[] buffer = new byte[500];

        int read = -1;
        while ((read = in.read(buffer)) > 0) {
            baos.write(buffer, 0, read);
        }
        in.close();

        Ticket newTicket = new Ticket();
        newTicket.setFileName("example");
        newTicket.setData(baos.toByteArray());
        ticketRepository.save(newTicket);

        return baos.toByteArray();
    }

Ticket entity:

    @Data
    @Entity
    public class Ticket {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String fileName;

    @Lob
    private byte[] data;

    @NotNull
    @JsonIgnore
    @Column(updatable = false)
    private LocalDateTime createAt;

    @NotNull
    @JsonIgnore
    private LocalDateTime updatedAt;
}

1 Answer 1

2

Here is an example how you can get a byte[] from PdfDocument:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Documentdocument = new Document();

PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);

document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk("Hello World", font);

document.add(chunk);
document.close(); 

pdfWriter.flush();

byte[] pdfAsBytes = baos.toByteArray();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.