Java: utiliser apache POI comment convertir un fichier ms word en pdf?


En utilisant apache POI comment convertir ms word fichier pdf?

J'utilise le code suivant mais cela ne fonctionne pas en donnant des erreurs, je suppose que j'importe les mauvaises classes?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.poi.hslf.record.Document;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;  
         Document document = new Document(); 

         try {  
             System.out.println("Starting the test");  
             fs = new POIFSFileSystem(new FileInputStream("/document/test2.doc"));  

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

             OutputStream file = new FileOutputStream(new File("/document/test.pdf")); 

             PdfWriter writer = PdfWriter.getInstance(document, file);  

             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);
                // CharacterRun run = pr.getCharacterRun(i);
                // run.setBold(true);
                // run.setCapitalized(true);
                // run.setItalic(true);
                 paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");  
             System.out.println("Length:" + paragraphs[i].length());  
             System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());  

             // add the paragraph to the document  
             document.add(new Paragraph(paragraphs[i]));  
             }  

             System.out.println("Document testing completed");  
         } catch (Exception e) {  
             System.out.println("Exception during test");  
             e.printStackTrace();  
         } finally {  
                         // close the document  
            document.close();  
                     }  
         }  
    }
Author: Murta, 2011-06-01

6 answers

L'a résolu

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;  
        Document document = new Document();

         try {  
             System.out.println("Starting the test");  
             fs = new POIFSFileSystem(new FileInputStream("D:/Resume.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, file);  

             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);
                // CharacterRun run = pr.getCharacterRun(i);
                // run.setBold(true);
                // run.setCapitalized(true);
                // run.setItalic(true);
                 paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");  
             System.out.println("Length:" + paragraphs[i].length());  
             System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());  

             // add the paragraph to the document  
             document.add(new Paragraph(paragraphs[i]));  
             }  

             System.out.println("Document testing completed");  
         } catch (Exception e) {  
             System.out.println("Exception during test");  
             e.printStackTrace();  
         } finally {  
                         // close the document  
            document.close();  
                     }  
         }  
    }
 9
Author: Harinder, 2011-06-02 05:14:26

Le code ci-dessous a fonctionné pour moi:

Public class DocToPdfConverter{

public static void main(String[] args) {

        String k=null;
        OutputStream fileForPdf =null;
        try {

            String fileName="/document/test2.doc";
            //Below Code is for .doc file 
            if(fileName.endsWith(".doc"))
            {
            HWPFDocument doc = new HWPFDocument(new FileInputStream(
                    fileName));
            WordExtractor we=new WordExtractor(doc);
            k = we.getText();

             fileForPdf = new FileOutputStream(new File(
                        "/document/DocToPdf.pdf")); 
            we.close();
            }

            //Below Code for 

            else if(fileName.endsWith(".docx"))
            {
                XWPFDocument docx = new XWPFDocument(new FileInputStream(
                        fileName));
                // using XWPFWordExtractor Class
                XWPFWordExtractor we = new XWPFWordExtractor(docx);
                 k = we.getText();

                 fileForPdf = new FileOutputStream(new File(
                            "/document/DocxToPdf.pdf"));    
                 we.close();
            }



            Document document = new Document();
            PdfWriter.getInstance(document, fileForPdf);

            document.open();

            document.add(new Paragraph(k));

            document.close();
            fileForPdf.close();



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 2
Author: Rohit Dubey, 2016-08-12 08:43:04

Cela a fonctionné Pour Moi: -

Source: - http://www.programcreek.com/java-api-examples/index.php?api=org.apache.poi.xwpf.converter.pdf.PdfConverter

package pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class PDF {
    public static void main(String[] args) throws Exception {
          String inputFile="D:/TEST.docx";
          String outputFile="D:/TEST.pdf";
          if (args != null && args.length == 2) {
            inputFile=args[0];
            outputFile=args[1];
          }
          System.out.println("inputFile:" + inputFile + ",outputFile:"+ outputFile);
          FileInputStream in=new FileInputStream(inputFile);
          XWPFDocument document=new XWPFDocument(in);
          File outFile=new File(outputFile);
          OutputStream out=new FileOutputStream(outFile);
          PdfOptions options=null;
          PdfConverter.getInstance().convert(document,out,options);
        }
}
 2
Author: Kushagra Sahni, 2017-04-18 12:32:40

Il y a plusieurs étapes ici:

  1. Lire le document Word en utilisant POI dans une forme agnostique de format
  2. Convertir un formulaire agnostique en PDF
  3. Écrire un PDF

Je ne sais pas si POI fera l'étape 2 pour vous. Je recommanderais autre chose, comme iText.

 1
Author: duffymo, 2011-06-01 13:19:01

En guise de remarque, il est également possible de lire du contenu à la volée directement à partir d'un flux de contenu Word/Excel au lieu de le lire à partir du système de fichiers et de le sérialiser sur disque, par exemple lors de la récupération de contenu à partir de référentiels CMIS:

Par exemple

 //HWPFDocument docx = new HWPFDocument(fs);  
 HWPFDocument docx = new HWPFDocument(doc.getContentStream().getStream()); 

(doc est de type {[1] } et dans ce cas, j'ai adapté votre code pour récupérer un fichier word d'un référentiel Alfresco au moyen d'opencmis et l'ai transformé en PDF)

HTH

 1
Author: theshadow, 2012-09-22 10:34:33

En plus de la réponse de Kushagra, voici les dépendances maven mises à jour:

    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>fr.opensagres.xdocreport.converter</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>fr.opensagres.poi.xwpf.converter.pdf</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
        <version>2.0.1</version>
    </dependency>
 1
Author: Erich13, 2018-05-24 09:35:35