如何使用itext将doc转换为pdf文件 [英] How to convert doc to pdf file using itext

查看:44
本文介绍了如何使用itext将doc转换为pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要如何使用 itext 将 doc 转换为 pdf 文件.

I need how to convert doc to pdf file using itext.

我正在使用以下代码,但它不起作用.我正在使用 itext 2.1.7.jar.

I am using the following code it is not working. i am using itext 2.1.7.jar.

出现以下错误:

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

推荐答案

您没有向 PDF 文档添加任何内容(只是一个空的新页面).要添加实际内容,请使用 add(Element) Document 类的方法.

You didn't add any content to the PDF document (just an empty new page). To add actual content, use the add(Element) method of the Document class.

这篇关于如何使用itext将doc转换为pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆