javapdfapache-commons-io

Images are not appearing good when converted from .docx to pdf


I converted .docx file to .pdf file, the text is converting fine, but the images in the .docx file is not appearing, instead it is represented as some special characters, below is my code:

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 PDFConversion {

    /**
     * 14. This method is used to convert the given file to a PDF format 15.
     * 
     * @param inputFile
     *            - Name and the path of the file 16.
     * @param outputFile
     *            - Name and the path where the PDF file to be saved 17.
     * @param isPictureFile
     *            18.
     */

    private void createPdf(String inputFile, String outputFile, boolean isPictureFile) {
        /**
         * 22. Create a new instance for Document class 23.
         */
        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();

            /**
             * 34. Proceed if the file given is a picture file 35.
             */
            if (isPictureFile) {
                pdfDocument.add(com.lowagie.text.Image.getInstance(inputFile));
            }

            /**
             * 41. Proceed if the file given is (.txt,.html,.doc etc) 42.
             */

            else {
                File file = new File(inputFile);
                pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils
                        .readFileToString(file)));      
            }
            pdfDocument.close();
            writer.close();
        } catch (Exception exception) {
            System.out.println("Document Exception!" + exception);
        }
    }

    public static void main(String args[]) {
        PDFConversion pdfConversion = new PDFConversion();
        pdfConversion.createPdf("C:/Users/LENOVO/Downloads/The_JFileChooser_Component.doc",
                "E:/The_JFileChooser_Component.pdf", false);
        // For other files
        // pdfConversion.createPdf("C:/shunmuga/sample.html",
        // "C:/shunmuga/sample.pdf", false);
    }
}

Solution

  • I'm not sure what it could be, but for some alternatives have a look at:

    If that's not enough it has sample source code for you to try.