2012-04-27 110 views
0

我需要如何使用itext將doc轉換爲pdf文件。我使用下面的代碼,它不工作。我正在使用itext 2.1.7.jar。下面的錯誤來了如何使用itext將文檔轉換爲pdf文件

Exception in thread "main" ExceptionConverter: java.io.IOException: The document 
    has no pages.at com.lowagie.text.pdf.PdfPages.writePageTree(Unknown Source) 
at com.lowagie.text.pdf.PdfWriter.close(Unknown Source) 
at com.lowagie.text.pdf.PdfDocument.close(Unknown Source) 
at com.lowagie.text.Document.close(Unknown Source) 

這裏是我的來源:

我在此先感謝
POIFSFileSystem fs = null; 
    Document document = new Document(); 
    try { 
     System.out.println("Starting the test"); 
     fs = new POIFSFileSystem(new FileInputStream("D:\\Result1.doc")); 

     HWPFDocument doc = new HWPFDocument(fs); 
     WordExtractor we = new WordExtractor(doc); 

     //OutputStream file = new FileOutputStream(new File("D:\\test.pdf")); 
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\test.pdf")); 
       Range range = doc.getRange(); 
     document.open(); 
     writer.setPageEmpty(true); 
     document.newPage(); 
     writer.setPageEmpty(true); 
     String[] paragraphs = we.getParagraphText(); 
     for (int i = 0; i < paragraphs.length; i++) { 
      org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i); 
      paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", ""); 
     System.out.println("Length:" + paragraphs[i].length()); 
     System.out.println("Paragraph" + i + ": " + paragraphs[i].toString()); 
     } 
     System.out.println("Document testing completed"); 
    } catch (Exception e) { 
     System.out.println("Exception during test"); 
     e.printStackTrace(); 
    } finally { 
     document.close(); 
    } 

請任何人的幫助。

回答

0

您沒有向PDF文檔添加任何內容(只是一個空白的新頁面)。要添加實際內容,請使用Document類的add(Element)方法。

+0

我在Result1.doc文件中添加了一些內容 – 2012-04-27 11:29:59

+0

對不起,我的意思是你沒有向PDF文檔添加任何內容,讓我編輯我的回覆。 – 2012-04-27 11:54:05

+0

是的,我沒有添加任何內容的PDF文件 – 2012-04-28 04:16:39