2016-08-08 12 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

これは間違っている:iTextの5、PdfDocument

PdfDocument pdf = new 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)の違いとは全く関係ありません。例外をスローするメソッドを使用しています。 JavaやAndroidで作業しているかどうかにかかわらず、これらの例外を処理する必要があります。

iTextとiTextGの違いはごくわずかです。 iTextとiTextGの別々のドキュメントを作成する理由はありません。

+0

ありがとうございます!私はドキュメンテーションに行きましたが、間違った場所にいると思います。ここで、私が[example](http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/examples/chapter-1)を見て、PDFを作成していたところです。 –

+1

あなたはiText(G)5とは異なるAPIを持つiText 7のドキュメントを見ていました(コードの先頭にあるコメントにあります)。 –

+0

@AmedeeVanGasse説明していただきありがとうございます。私は最後のバージョンを使う方が良いと思ったので、混乱してしまったのです。もう一度、ありがとう! –

関連する問題