Java: Need to create PDF from byte-Array

后端 未结 4 1866
逝去的感伤
逝去的感伤 2021-02-02 13:20

From a DB2 table I\'ve got blob which I\'m converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.

This

相关标签:
4条回答
  • 2021-02-02 13:51

    Read from file or string to bytearray.

    byte[] filedata = null;
    String content = new String(bytearray);
    content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
    String[] arrOfStr = content.split("\n");
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
        // setting font family and font size
        cs.beginText(); 
        cs.setFont(PDType1Font.HELVETICA, 14);
        cs.setNonStrokingColor(Color.BLACK);
        cs.newLineAtOffset(20, 750);
        for (String str: arrOfStr) {
            cs.newLineAtOffset(0, -15);
            cs.showText(str);
        }
        cs.newLine();
        cs.endText();
    }
    document.save(znaFile);
    document.close();
    
    0 讨论(0)
  • 2021-02-02 14:06
     public static String getPDF() throws IOException {
    
            File file = new File("give complete path of file which must be read");
            FileInputStream stream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int bytesRead;enter code here
            while ((bytesRead = stream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            System.out.println("it came back"+baos);
            byte[] buffer1= baos.toByteArray();
            String fileName = "give your filename with location";
    
            //stream.close();
            
            
             FileOutputStream outputStream =
                        new FileOutputStream(fileName);
             
             outputStream.write(buffer1);
            
             return fileName;
            
        }
    
    0 讨论(0)
  • 2021-02-02 14:12

    One can utilize the autoclosable interface that was introduced in java 7.

    try (OutputStream out = new FileOutputStream("out.pdf")) {
       out.write(bArray);
    }
    
    0 讨论(0)
  • 2021-02-02 14:15

    Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:

    OutputStream out = new FileOutputStream("out.pdf");
    out.write(bArray);
    out.close();
    
    0 讨论(0)
提交回复
热议问题