简体   繁体   中英

Converting word(.docx) to pdf using Apache POI and itext

In my java web application i have a Persian template word(docx) document as a contract that customize it for my users whit their data using APACHE-POI and after that i have to convert it to pdf in order to prevent the file from being distorted by the operator. I tried to convert it using itext but i couldnt get success and couldnt find something helpful, can someone suggest a way for doing the conversion using itext or can anyone tell me if there is any other way to prevent the file from being distorted without doing conversion?

Edit note:I did the conversion whit the following codes below but now i have lots of question marks in my pdf file, can anyone help??does itext supports persian or RTL languages?how chan i solve this problem? I am using version 5.0.6 of iText!!

convertWordToPdf("D:/PrivateBanking/docxCo.docx","D:/PrivateBanking/docxCo.pdf");

public static void convertWordToPdf(String src, String desc){
        try{
            //create file inputstream object to read data from file
            FileInputStream fs=new FileInputStream(src);
            //create document object to wrap the file inputstream object
            XWPFDocument doc=new XWPFDocument(fs);
            //72 units=1 inch
            Document pdfdoc=new Document(PageSize.A4,72,72,72,72);
            //create a pdf writer object to write text to mypdf.pdf file
            PdfWriter pwriter=PdfWriter.getInstance(pdfdoc, new FileOutputStream(desc));
            //specify the vertical space between the lines of text
            pwriter.setInitialLeading(20);
            //get all paragraphs from word docx
            List<XWPFParagraph> plist=doc.getParagraphs();

            //open pdf document for writing
            pdfdoc.open();
            for (int i = 0; i < plist.size(); i++) {
                //read through the list of paragraphs
                XWPFParagraph pa = plist.get(i);
                //get all run objects from each paragraph
                List<XWPFRun> runs = pa.getRuns();
                //read through the run objects
                for (int j = 0; j < runs.size(); j++) {
                    XWPFRun run=runs.get(j);
                    //get pictures from the run and add them to the pdf document
                    List<XWPFPicture> piclist=run.getEmbeddedPictures();
                    //traverse through the list and write each image to a file
                    Iterator<XWPFPicture> iterator=piclist.iterator();
                    while(iterator.hasNext()){
                        XWPFPicture pic=iterator.next();
                        XWPFPictureData picdata=pic.getPictureData();
                        byte[] bytepic=picdata.getData();
                        Image imag=Image.getInstance(bytepic);
                        pdfdoc.add(imag);

                    }
                    //get color code
                    int color=getCode(run.getColor());
                    //construct font object
                    Font f=null;
                    if(run.isBold() && run.isItalic())
                        f= FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.BOLDITALIC, new BaseColor(color));
                    else if(run.isBold())
                        f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.BOLD, new BaseColor(color));
                    else if(run.isItalic())
                        f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.ITALIC, new BaseColor(color));
                    else if(run.isStrike())
                        f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.STRIKETHRU, new BaseColor(color));
                    else
                        f=FontFactory.getFont(FontFactory.TIMES_ROMAN,run.getFontSize(),Font.NORMAL, new BaseColor(color));
                    //construct unicode string
                    String text=run.getText(-1);
                    byte[] bs;
                    if (text!=null){
                        bs=text.getBytes();
                        String str=new String(bs,"UTF-8");
                        //add string to the pdf document
                        Chunk chObj1=new Chunk(str,f);
                        pdfdoc.add(chObj1);
                    }

                }
                //output new line
                pdfdoc.add(new Chunk(Chunk.NEWLINE));
            }
            //close pdf document
            pdfdoc.close();
        }catch(Exception e){e.printStackTrace();}
    }

 public static int getCode(String code){
        int colorCode;
        if(code!=null)
            colorCode=Long.decode("0x"+code).intValue();
        else
            colorCode=Long.decode("0x000000").intValue();
        return colorCode;
    }

You need to install MS Office before running, then:

import com.documents4j.api.DocumentType; 
import com.documents4j.api.IConverter; 
import com.documents4j.job.LocalConverter;
import org.apache.commons.io.output.ByteArrayOutputStream;

import java.io.*; 
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; 
import java.util.concurrent.TimeUnit;

public class Converter{
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();

        InputStream in = new BufferedInputStream(new FileInputStream("d:\\input.docx"));
        IConverter converter = LocalConverter.builder()
                .baseFolder(new File("D:\\input"))
                .workerPool(20, 25, 2, TimeUnit.SECONDS)
                .processTimeout(5, TimeUnit.SECONDS)
                .build();

        Future<Boolean> conversion = converter
                .convert(in).as(DocumentType.MS_WORD)
                .to(bo).as(DocumentType.PDF)
                .prioritizeWith(1000) // optional
                .schedule();
        conversion.get();
        try (OutputStream outputStream = new FileOutputStream("D:\\output.pdf")) {
            bo.writeTo(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        in.close();
        bo.close();
    }
}

These are the necessary maven dependencies:

<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-api</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-util-conversion</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-util-all</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-local</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.8.0-beta2</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.8.0-beta2</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-util-standalone</artifactId>
    <version>1.0.3</version>
</dependency>
<dependency>
    <groupId>com.documents4j</groupId>
    <artifactId>documents4j-transformer-msoffice-word</artifactId>
    <version>1.0.3</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>

Enjoy!

If you want to convert docx to pdf using APACHE-POI then you will be needing following jars with suitable versions

org.apache.poi.xwpf.converter.core-x.x.x.jar
org.apache.poi.xwpf.converter.pdf-x.x.x.jar

If you want to using some other library then you can try Docx4j You can find an example here: https://www.docx4java.org/trac/docx4j

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM