2016-08-08 7 views
0

Android에서 PDF를 만들려고하지만 버튼을 누르면 휴대 전화에 저장하지 말고 일부 정보 만 표시하려고합니다. 이 오류가 발생합니다 :이 오류가 발생하는 이유 : 처리되지 않은 예외 : Android에서 com.itextpdf.text.DocumentException?

Unhandled exception: com.itextpdf.text.DocumentException 

그러나 나는 그것이 왜 발생하는지 이해하지 못합니다. 다음 코드를 가지고 있습니다 :

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
PdfDocument pdf = new PdfDocument(); 

PdfWriter pdfWriter = PdfWriter.getInstance(pdf, baos); //Error here 
pdf.open(); 
pdf.add(new Paragraph("Hello world")); //Error here 
pdf.close(); 

byte[] pdfByteArray = baos.toByteArray(); 

왜이 오류가 발생합니까? itextg 라이브러리를 잘못 사용하고 있습니까? 이 오류에 대한 정보를 찾을 수 없습니다.

P.S : 나는 오류가 오류가이 사실로 제작 될 수 있다면 내가 모르는 itext 대신 itextg와 관련되어 있음을 볼 수 있었다.

미리 감사드립니다.

답변

1

이것은 잘못된 것입니다 :

PdfDocument pdf = new PdfDocument(); 

iText를 5 년 PdfDocument 클래스 만이 iText에 의해 내부적으로을 사용하는 것입니다. 대신 Document 클래스를 사용해야합니다.

은 다음과 같이 코드를 적응 :

try { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    Document document = new Document(); 
    PdfWriter pdfWriter = PdfWriter.getInstance(document, baos); //Error here 
    document.open(); 
    document.add(new Paragraph("Hello world")); //Error here 
    document.close(); 
    byte[] pdfByteArray = baos.toByteArray(); 
} 
catch (DocumentException de) { 
    // handle the exception when something goes wrong on the iText level. 
    // for instance: you add one element to another element that is incompatible 
} 
catch (IOException) { 
    // handle the exception when something goes wrong on the IO level. 
    // for instance: you try to write to a file in a folder that doesn't exist 
} 

documentation을 읽어 보시기 바랍니다 조심스럽게 자신에 실험을 시작하기 전에. Hello World 예제는 Q & As의 Getting Started 섹션에서 찾을 수 있습니다.

실제 문제는 당신이 필요가 없다는 사실에 의해 발생되는 IOException 또는 DocumentException 다루는 try/catch (또는 throws).

귀하의 오류는 iText (Java)와 iTextG (Android)의 차이와는 완전히 관련이 없습니다. 예외를 throw하는 메서드를 사용하고 있습니다. Java 또는 Android에서 작업하는지 여부에 관계없이 이러한 예외를 처리해야합니다.

iText와 iTextG에는 약간의 차이가 있습니다. 별도의 iText 및 iTextG 문서를 가질 이유가 없습니다.

+0

대단히 감사합니다. 나는 문서에 갔지만 생각했던 잘못된 곳으로 갔다. 여기 내가 PDF를 만들려고 할 때 [예제] (http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/examples/chapter-1)를 보았습니다. –

+1

iText (G) 5와 다른 API를 사용하는 iText 7 설명서를 보았습니다 (코드 상단의 주석에 표시되어 있음). –

+0

@AmedeeVanGasse 설명해 주셔서 감사합니다. 나는 마지막 버전을 사용하는 것이 더 낫다고 생각했기 때문에 혼란 스러웠습니다. 다시 고마워! –