2015-07-13 4 views
2

Я пытаюсь загрузить в файл PDF. Я написали кодPDF-файл с PDFBox пуст

public ByteArrayOutputStream createPDF(String text) throws IOException, COSVisitorException { 

    PDDocument document; 
    PDPage page; 
    PDFont font1; 
    PDPageContentStream contentStream; 
    ByteArrayOutputStream output = new ByteArrayOutputStream(); 
    document = new PDDocument(); 


    try { 
    page = new PDPage();  
    document.addPage(page); 
    contentStream = new PDPageContentStream(document, page); 

    contentStream.beginText(); 
    contentStream.moveTextPositionByAmount(100, 700); 
    contentStream.drawString("Hello World Hello World Hello World Hello World Hello World"); 
    contentStream.endText(); 
    System.out.println("output " + output); 
    document.save(output); 
    document.close(); 
    contentStream.close();  

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

    } finally 
    { 
    logInfo("output completed"); 
    } 
    return output; 
} 

Произведенный PDF-файл пуст. Содержание файла:

%▒▒▒▒ 
1 0 obj 
<< 
/Type /Catalog 
/Version /1.4 
/Pages 2 0 R 
>> 
endobj 
2 0 obj 
<< 
/Type /Pages 
/Kids [3 0 R] 
/Count 1 
>> 
endobj 
3 0 obj 
<< 
/Type /Page 
/MediaBox [0.0 0.0 612.0 792.0] 
/Parent 2 0 R 
/Contents 4 0 R 
/Resources 5 0 R 
>> 
endobj 
4 0 obj 
<< 
/Filter [/FlateDecode] 
/Length 6 0 R 
>> 
stream 
x▒ 
endstream 
endobj 
5 0 obj 
<< 
>> 
endobj 
6 0 obj 
8 
endobj 
xref 
0 7 
0000000000 65535 f 
0000000015 00000 n 
0000000078 00000 n 
0000000135 00000 n 
0000000247 00000 n 
0000000333 00000 n 
0000000354 00000 n 
trailer 
<< 
/Root 1 0 R 
/ID [<C68578F989B81BF7DD279AE1745F6E8F> <D41D8CD98F00B204E9800998ECF8427E>] 
/Size 7 
>> 
startxref 
371 
%%EOF 

ответ

4

Вы сделали две ошибки:

  1. Вы закрыли contentStream после сохранения документа, а не раньше.

  2. Вы не установили ни одного шрифта.

Код, который работает для меня (обработка исключений удалены):

PDDocument document; 
PDPage page; 
PDPageContentStream contentStream; 
document = new PDDocument(); 

page = new PDPage(); 
document.addPage(page); 
contentStream = new PDPageContentStream(document, page); 

contentStream.setFont(PDType1Font.COURIER, 10); 

contentStream.beginText(); 
contentStream.moveTextPositionByAmount(100, 700); 
contentStream.drawString("Hello World Hello World Hello World Hello World Hello World"); 
contentStream.endText(); 
contentStream.close(); 
document.save(....); 
document.close(); 
Смежные вопросы