2012-08-10 14 views
5

Ho bisogno di convertire iTextPDF documento file byte [] dopo che è stato creato in memoria di . Ho già provato che non ho problemi con la creazione di PDF in modo corretto. Il problema è come convertirlo in array di byte per archiviare in DB.Come convertire iTextPDF Documento di array di byte

Ecco il mio codice:

Document generatedDocument = reportService.generateRequestForm(scdUser, jsonObject, 0, null); 
reportService.generateRequestForm(scdUser, jsonObject, 0, null); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
PdfWriter pdfWriter = PdfWriter.getInstance(generatedDocument, baos); 
generatedDocument.open(); 
document.setDocument(baos.toByteArray()); // stores as blob 

ho avuto valore nulla alla banca dati blob colonna.

Ecco il mio oggetto di dominio Document Object

dominio dei documenti

@Entity 
@Table(name = "document") 
public class Document implements java.io.Serializable { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "document_id", nullable = false) 
    private int documentId; 
    @Column(name = "document_name", nullable = false, length = 65535) 
    private String documentName; 
    @Column(name = "document_type", nullable = false) 
    private int documentType; 
    @Temporal(TemporalType.TIMESTAMP) 
    @Column(name = "upload_date", nullable = false, length = 19) 
    private Date uploadDate = new Date(); 
    @Column(name = "document", nullable = false) 
    private byte[] document; // BLOB COLUMN 
    @Column(name = "document_size", nullable = false) 
    private long documentSize; 
    @Column(name = "title", nullable = true, insertable = true, updatable = true, length = 65535, precision = 0) 
    private String title; 
    @Column(name = "tag", nullable = true, insertable = true, updatable = true, length = 65535, precision = 0) 
    private String tag; 
    @Column(name = "description", nullable = true, insertable = true, updatable = true, length = 65535, precision = 0) 
    private String description; 
    @Column(name = "shared", nullable = false, insertable = true, updatable = true, length = 1, precision = 0) 
    private boolean shared = false; 
    @Column(name = "status", nullable = false) 
    private int status = DocumentStatus.READY.getStatus(); 


    public int getDocumentId() { 
     return this.documentId; 
    } 

    public void setDocumentId(int documentId) { 
     this.documentId = documentId; 
    } 

    public String getDocumentName() { 
     return this.documentName; 
    } 

    public void setDocumentName(String documentName) { 
     this.documentName = documentName; 
    } 

    public int getDocumentType() { 
     return this.documentType; 
    } 

    public void setDocumentType(int documentType) { 
     this.documentType = documentType; 
    } 

    public Date getUploadDate() { 
     return this.uploadDate; 
    } 

    public void setUploadDate(Date uploadDate) { 
     this.uploadDate = uploadDate; 
    } 

    public byte[] getDocument() { 
     return this.document; 
    } 

    public void setDocument(byte[] document) { 
     this.document = document; 
    } 

    public long getDocumentSize() { 
     return this.documentSize; 
    } 

    public void setDocumentSize(long documentSize) { 
     this.documentSize = documentSize; 
    } 

    public String getTag() { 
     return tag; 
    } 

    public void setTag(String tag) { 
     this.tag = tag; 
    } 

    public String getTitle() { 
     return title; 
    } 

    public void setTitle(String title) { 
     this.title = title; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 

    public boolean getShared() { 
     return shared; 
    } 

    public void setShared(boolean shared) { 
     this.shared = shared; 
    } 


    public int getStatus() { 
     return status; 
    } 

    public void setStatus(int status) { 
     this.status = status; 
    } 


} 
+0

guarda la domanda, poi guarda l'ultima frase .. – Eugene

+0

sembra che il documento non verrà generato in un primo momento a causa di tale errore del database. –

+0

@Eugene è lo stesso; Sto persistendo byte [] nella colonna blob. – talha06

risposta

2

Dai commenti sembra che non ha nulla a che fare il modo in PDF viene generata in fase di esecuzione, ma invece il modo in cui è memorizzato nel DB. È necessario fornire anche questo codice.

Ecco quello che ho in realtà (la mia prova):

Il titolare:

import java.io.Serializable; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 



@Entity 
public class PDFHolder implements Serializable { 

@Id 
@GeneratedValue(strategy=GenerationType.AUTO) 
private long id; 

@Column(columnDefinition = "LONGBLOB") 
private byte[] documentPDF; 

public byte[] getDocumentPDF() { 
    return documentPDF; 
} 

public void setDocumentPDF(byte[] documentPDF) { 
    this.documentPDF = documentPDF; 
} 

public long getId() { 
    return id; 
} 

public void setId(long id) { 
    this.id = id; 
} 
} 

repository, che fa il salvataggio:

@Repository 
public interface PDFHolderRepository extends JpaRepository<PDFHolder, Long> {} 

e l'inserto attuale:

private void generateDatabaseRows() { 

    try{ 
     String urlPDF = "http://cetatenie.just.ro/LinkClick.aspx?fileticket=K13DZkoIE2o%3d&tabid=57&mid=593"; 
     URL url = new URL(urlPDF); 

     ByteBuffer byteBufferResponse = this.getAsByteArray(url.openConnection()); 
     byte [] responseArray = byteBufferResponse.array(); 
     System.out.println("Size of the PDF : " + responseArray.length); 

     // Save it to DB 
     PDFHolder pdfHolder = new PDFHolder(); 
     pdfHolder.setDocumentPDF(responseArray); 

     pdfHolderRepository.save(pdfHolder); 

    } catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 


private ByteBuffer getAsByteArray(final URLConnection urlConnection) throws IOException { 
    final ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(); 
    final InputStream inputStream = urlConnection.getInputStream(); 
    final byte[] buf = new byte[1024]; 
    int len; 
    while (true) { 
     len = inputStream.read(buf); 
     if (len == -1) { 
      break; 
     } 
     tmpOut.write(buf, 0, len); 
    } 
    tmpOut.close(); 
    return ByteBuffer.wrap(tmpOut.toByteArray(), 0, tmpOut.size()); 
} 

di Naturalmente ho un repository @Autowired in questa classe:

@Autowired 
PDFHolderRepository pdfHolderRepository; 

MySQL stores the byte array

+0

modificato il primo post .. – talha06

+0

@ talha06 mostraci ESATTAMENTE dove ottieni il null. – Eugene

+0

Ottengo null quando recupero il documento dal DB. (Inoltre vedo null quando su GUI - MySQL Workbench) continuo PDF a DB usando Hibernate. Quando eseguo il debug del codice, vedo che il documento è stato generato correttamente. Quindi voglio imparare come posso convertire con successo il documento iTextPDF in array di byte al fine di persistere correttamente. – talha06

12

Ho avuto un problema simile ... mi piacerebbe creare il documento e all'interno della classe in cui ho creato, ho potuto salvarla su File, e ha funzionato alla grande. Tuttavia, quando ho provato a restituirlo come stream, otterrei un valore nullo.

Il problema era che una volta chiuso il documento (document.close()), avrebbe chiuso anche il flusso.

La soluzione era creare un oggetto ByteArrayOutputStream quando ho creato il documento e l'output PdfWriter. Potrei quindi fare quello che volevo con i byte PDF ... nel mio caso li ho convertiti in uno StreamedContent da inviare all'utente.

Creare una variabile per contenere i byte:

private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

avere l'output PDFWriter i dati al byte [] in quanto crea il documento:

Document document = new Document(PageSize.LETTER, 0.75F, 0.75F, 0.75F, 0.75F); 
    PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open() 

    document.open(); 
    createPDF(document); // Whatever function that you use to create your PDF 
    document.close(); 

volta che hai finito la generazione del PDF, prendi semplicemente i byte e falli con loro come preferisci.

byte[] pdfBytes = byteArrayOutputStream.toByteArray(); 

non so che cosa il vostro classe ReportService assomiglia, ma questo può essere un buon posto dove metterlo.

Spero che questo aiuti.

+0

Ottima risposta! Mi ha aiutato molto! C'è un modo elegante per impostare il nome del file? Chrome lo scarica automaticamente come "something.pdf". –

Problemi correlati