1

下面是我用来将word文档转换为pdf的代码。编译代码后,生成PDF文件。但是该文件包含一些垃圾字符以及 word 文档内容。请帮助我知道我应该做些什么修改来摆脱垃圾字符。我使用的代码是:

import com.lowagie.text.Document; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.pdf.PdfWriter; 
import java.io.File; 
import java.io.FileOutputStream; 



public class PdfConverter 
{

    private void createPdf(String inputFile, String outputFile)//, boolean isPictureFile) 
    {
        Document pdfDocument = new Document(); 
        String pdfFilePath = outputFile; 
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath); 
            PdfWriter writer = null; 
            writer = PdfWriter.getInstance(pdfDocument, fileOutputStream); 
            writer.open(); 
            pdfDocument.open(); 
            /*if (isPictureFile) 
            { 
            pdfDocument.add(com.lowagie.text.Image.getInstance(inputFile)); 
                } 
            else 
            { */
            File file = new File(inputFile); 
    pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file))); 
                //} 
            pdfDocument.close(); 
            writer.close(); 
            System.out.println("PDF has been generted"); 
            } 
            catch (Exception exception) 
            { 
            System.out.println("Document Exception!" + exception); 
            } 
            } 

    public static void main(String args[]) 
    { 
    PdfConverter pdfConversion = new PdfConverter(); 
    pdfConversion.createPdf("C:/test.doc", "C:/test.pdf");//, true); 

        }

    }

谢谢你的帮助。

4

2 回答 2

2

只是因为你命名你的类 PdfConverter 你没有。您所做的就是将二进制内容作为字符串读取并将其写为一个段落(这就是您所看到的)。这种方法肯定不会成功。有关类似问题,请参阅https://stackoverflow.com/questions/437394 。

如果您只对 word 文档的内容感兴趣,您可能希望尝试使用Apache POI(Microsoft 文档的 Java API)来阅读您的文档,而不是二进制级别,而是高度抽象级别。如果您的 Word 文档具有简单(我的意思是非常简单)的结构,您可能会得到合理的结果。

于 2012-08-07T10:58:46.727 回答
1

为此,您必须正确读取 doc 文件,然后使用读取的数据创建 PDF 文件。

您现在正在做的是从 doc 文件中读取数据,该文件具有垃圾值,因为您没有使用适当的 API 来读取数据,然后将获得的垃圾数据存储在 PDF 文件中。因此问题。

于 2012-08-07T12:33:29.753 回答