2012-08-10 15 views
5

tôi cần phải chuyển đổi Document iTextPDF tập tin để byte [] sau khi nó được tạo ra trong nhớ. Tôi đã thử nghiệm rằng tôi không có vấn đề với việc tạo PDF đúng cách. Vấn đề là làm thế nào để chuyển đổi nó thành mảng byte để lưu trữ trong DB.Làm thế nào để chuyển đổi tài liệu iTextPDF để Byte mảng

Dưới đây là mã của tôi:

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 

tôi có giá trị của rỗng tại cơ sở dữ liệu blob cột.

Dưới đây là của tôi đối tượng miền Document:

Document miền Object

@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

xem xét câu hỏi, sau đó xem câu cuối cùng của bạn .. – Eugene

+0

có vẻ như tài liệu sẽ không được tạo lúc đầu do nguyên nhân của lỗi cơ sở dữ liệu đó. –

+0

@Eugene giống nhau; Tôi kiên trì byte [] để blob cột. – talha06

Trả lời

2

Từ những ý kiến ​​có vẻ như nó không có gì để làm cách PDF được tạo ra trong thời gian chạy, nhưng thay vào đó là cách nó được lưu trữ trong DB. Bạn cũng cần phải cung cấp mã đó.

Dưới đây là những gì tôi có thực sự (thử nghiệm của tôi):

Các Chủ:

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; 
} 
} 

Kho lưu trữ, mà không tiết kiệm:

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

Và chèn thực tế:

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()); 
} 

Trong số Tất nhiên tôi có một kho lưu trữ @Autowired trong lớp này:

@Autowired 
PDFHolderRepository pdfHolderRepository; 

MySQL stores the byte array

+0

đã chỉnh sửa bài đăng đầu tiên .. – talha06

+0

@ talha06 hiển thị cho chúng tôi CHÍNH XÁC nơi bạn nhận được giá trị rỗng. – Eugene

+0

Tôi nhận được null khi tôi lấy tài liệu từ DB. (Ngoài ra tôi thấy null khi ở GUI - MySQL Workbench) Tôi vẫn tồn tại PDF để DB bằng cách sử dụng Hibernate. Khi tôi gỡ lỗi mã, tôi thấy tài liệu được tạo thành công. Vì vậy, tôi muốn tìm hiểu làm thế nào tôi có thể chuyển đổi thành công tài liệu iTextPDF thành mảng byte để duy trì đúng cách. – talha06

12

Tôi đã có một vấn đề tương tự ... Tôi muốn tạo ra các tài liệu và bên trong lớp mà tôi tạo ra nó, tôi có thể lưu nó vào File và nó hoạt động rất tốt. Tuy nhiên, khi tôi cố gắng trả lại nó như là một dòng tôi sẽ nhận được một giá trị null.

Vấn đề là khi Tài liệu đã bị đóng (document.close()), nó cũng sẽ đóng Luồng.

Công việc xung quanh là tạo một ByteArrayOutputStream khi tôi tạo Tài liệu và có đầu ra PdfWriter cho nó. Sau đó tôi có thể làm bất cứ điều gì tôi muốn với các byte PDF ... trong trường hợp của tôi, tôi chuyển đổi chúng thành một StreamedContent để gửi cho người dùng.

Tạo một biến để giữ byte:

private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

Có đầu ra PdfWriter dữ liệu vào byte [] vì nó tạo ra tài liệu:

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(); 

Khi bạn đã thực hiện tạo ra PDF, chỉ cần nhận được các Byte và làm với họ như bạn sẽ.

byte[] pdfBytes = byteArrayOutputStream.toByteArray(); 

Tôi không biết lớp reportService của bạn trông như thế nào, nhưng đây có thể là nơi tốt để đặt nó.

Hy vọng điều này sẽ hữu ích.

+0

Câu trả lời hay! Giúp tôi rất nhiều! Có một số cách thanh lịch để thiết lập tên của tập tin? Chrome tự động tải xuống "something.pdf". –