2013-02-22 12 views
8

Utilizzando pdfbox, è possibile convertire un PDF (o un byte PDF []) in un byte di immagine []? Ho esaminato diversi esempi online e gli unici che posso trovare descrivono come scrivere direttamente il file convertito nel filesystem o convertirlo in un oggetto AWT Java.pdfbox converte pdf in image byte []

Preferisco non incorrere nell'IO di scrivere un file di immagine nel filesystem, leggere in un byte [] e quindi cancellarlo.

Quindi questo che posso fare:

String destinationImageFormat = "jpg"; 
boolean success = false; 
InputStream is = getClass().getClassLoader().getResourceAsStream("example.pdf"); 
PDDocument pdf = PDDocument.load(is, true); 

int resolution = 256; 
String password = ""; 
String outputPrefix = "myImageFile"; 

PDFImageWriter imageWriter = new PDFImageWriter();  

success = imageWriter.writeImage(pdf, 
        destinationImageFormat, 
        password, 
        1, 
        2, 
        outputPrefix, 
        BufferedImage.TYPE_INT_RGB, 
        resolution); 

Oltre a questo:

InputStream is = getClass().getClassLoader().getResourceAsStream("example.pdf"); 

PDDocument pdf = PDDocument.load(is, true); 
List<PDPage> pages = pdf.getDocumentCatalog().getAllPages(); 

for (PDPage page : pages) 
{ 
    BufferedImage image = page.convertToImage(); 
} 

Dove io non sono chiare su è come trasformata della BufferedImage in un byte []. So che questo è trasformato in un flusso di output di file in imageWriter.writeImage(), ma non sono chiaro su come funziona l'API.

risposta

11

È possibile utilizzare ImageIO.write per scrivere su un OutputStream. Per ottenere un byte [], utilizzare un ByteArrayOutputStream, quindi chiamare suByteArray() su di esso.

+1

Grazie. Funziona come previsto. Se avessi abbastanza reputazione, ti voterei, ma questo è il mio primo post su StackOverflow. – user2100746

+0

Prego; dovresti essere in grado di contrassegnarlo come accettato. – aditsu

+0

@ user2100746 dovresti contrassegnare la risposta come accettata :) – Genjuro

0
try {   
       PDDocument document = PDDocument.load(PdfInfo.getPDFWAY()); 
       if (document.isEncrypted()) { 
        document.decrypt(PdfInfo.getPASSWORD()); 
       } 
       if ("bilevel".equalsIgnoreCase(PdfInfo.getCOLOR())) { 
        PdfInfo.setIMAGETYPE(BufferedImage.TYPE_BYTE_BINARY); 
       } else if ("indexed".equalsIgnoreCase(PdfInfo.getCOLOR())) { 
        PdfInfo.setIMAGETYPE(BufferedImage.TYPE_BYTE_INDEXED); 
       } else if ("gray".equalsIgnoreCase(PdfInfo.getCOLOR())) { 
        PdfInfo.setIMAGETYPE(BufferedImage.TYPE_BYTE_GRAY); 
       } else if ("rgb".equalsIgnoreCase(PdfInfo.getCOLOR())) { 
        PdfInfo.setIMAGETYPE(BufferedImage.TYPE_INT_RGB); 
       } else if ("rgba".equalsIgnoreCase(PdfInfo.getCOLOR())) { 
        PdfInfo.setIMAGETYPE(BufferedImage.TYPE_INT_ARGB); 
       } else { 
        System.exit(2); 
       } 
       PDFImageWriter imageWriter = new PDFImageWriter(); 
       boolean success = imageWriter.writeImage(document, PdfInfo.getIMAGE_FORMAT(),PdfInfo.getPASSWORD(), 
         PdfInfo.getSTART_PAGE(),PdfInfo.getEND_PAGE(),PdfInfo.getOUTPUT_PREFIX(),PdfInfo.getIMAGETYPE(),PdfInfo.getRESOLUTION()); 
       if (!success) { 
        System.exit(1); 
       } 
       document.close(); 

     } catch (IOException | CryptographyException | InvalidPasswordException ex) { 
      Logger.getLogger(PdfToImae.class.getName()).log(Level.SEVERE, null, ex); 
     } 
public class PdfInfo { 
    private static String PDFWAY;  
    private static String OUTPUT_PREFIX; 
    private static String PASSWORD; 
    private static int START_PAGE=1; 
    private static int END_PAGE=Integer.MAX_VALUE; 
    private static String IMAGE_FORMAT="jpg"; 
    private static String COLOR="rgb"; 
    private static int RESOLUTION=256; 
    private static int IMAGETYPE=24; 
    private static String filename; 
    private static String filePath=""; 
} 
0

Aggiungere dipendenza Maven:

<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox --> 
    <dependency> 
     <groupId>org.apache.pdfbox</groupId> 
     <artifactId>pdfbox</artifactId> 
     <version>2.0.1</version> 
    </dependency> 

E, conver un PDF to Image:

import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.rendering.PDFRenderer; 
import javax.imageio.ImageIO; 

private List<String> savePDF(String filePath) throws IOException { 
    List<String> result = Lists.newArrayList(); 

    File file = new File(filePath); 

    PDDocument doc = PDDocument.load(file); 
    PDFRenderer renderer = new PDFRenderer(doc); 

    int pageSize = doc.getNumberOfPages(); 
    for (int i = 0; i < pageSize; i++) { 
     String pngFileName = file.getPath() + "." + (i + 1) + ".png"; 

     FileOutputStream out = new FileOutputStream(pngFileName); 
     ImageIO.write(renderer.renderImageWithDPI(i, 96), "png", out); 
     out.close(); 

     result.add(pngFileName); 
    } 
    doc.close(); 
    return result; 
} 

EDIT:

import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.rendering.PDFRenderer; 
import javax.imageio.ImageIO; 

private List<String> savePDF(String filePath) throws IOException { 
    List<String> result = Lists.newArrayList(); 

    File file = new File(filePath); 

    PDDocument doc = PDDocument.load(file); 
    PDFRenderer renderer = new PDFRenderer(doc); 

    int pageSize = doc.getNumberOfPages(); 
    for (int i = 0; i < pageSize; i++) { 
     String pngFileName = file.getPath() + "." + (i + 1) + ".png"; 

     ByteArrayOutputStream out = new ByteArrayOutputStream(pngFileName); 
     ImageIO.write(renderer.renderImageWithDPI(i, 96), "png", out); 

     out.toByteArray(); // here you can get a byte array 

     out.close(); 

     result.add(pngFileName); 
    } 
    doc.close(); 
    return result; 
} 
+0

L'OP ha chiesto un modo per avere pdfbox per il rendering di un pdf direttamente su un byte [] ', non su un file. La tua risposta, d'altra parte, mostra solo un altro modo per renderlo in un file. – mkl

+0

Sostituisci FileOutputStream in ByteArrayOutputStream – BeeNoisy

+0

'" ByteArrayOutputStream out = new ByteArrayOutputStream (pngFileName) "' - 'ByteArrayOutputStream' ha solo due costruttori, uno senza parametri e uno con un parametro' int'. Quindi, la tua chiamata usando un parametro 'String' non verrà compilata nemmeno a meno che tu non intenda un' ByteArrayOutputStream' diverso da quello in 'java.io'. – mkl

Problemi correlati