在java..issue中将docx文件转换为pdf

时间:2017-04-06 07:09:28

标签: java

我正在开发一个需要将docx文件转换为pdf的项目。我发现相同的问题已经发布并使用了“Kishan C S”提供的代码。它使用docx4J2.8.1 代码工作正常,生成了pdf,但我遇到的唯一问题是docx文件包含未转换的logo.jpg(图像标题部分)。只有文本格式转换为pdf。 我发布了我用过的代码。请让我知道如何解决问题

P.S:链接我提到Convert docx file into PDF with Java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Level; 
import org.apache.log4j.LogManager; 
import org.apache.log4j.Logger; 
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings; 
import org.docx4j.fonts.IdentityPlusMapper; 
import org.docx4j.fonts.Mapper; 
import org.docx4j.fonts.PhysicalFont; 
import org.docx4j.fonts.PhysicalFonts; 
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class DocxConverter {


    public static void main(String[] args) throws FileNotFoundException, Docx4JException, Exception {
        InputStream is = new FileInputStream(new File("D:\\Test\\C_IN0004_AppointmentLetter.docx"));
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
            List sections = wordMLPackage.getDocumentModel().getSections();
            for (int i = 0; i < sections.size(); i++) {
                wordMLPackage.getDocumentModel().getSections().get(i).getPageDimensions();
            }
            Mapper fontMapper = new IdentityPlusMapper();
            PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");//set your desired font 
            fontMapper.getFontMappings().put("Algerian", font);
            wordMLPackage.setFontMapper(fontMapper);
            PdfSettings pdfSettings = new PdfSettings();
            org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
            //To turn off logger
            List<Logger> loggers = Collections.<Logger> list(LogManager.getCurrentLoggers());
            loggers.add(LogManager.getRootLogger());
            for (Logger logger : loggers) {
                logger.setLevel(Level.OFF);
            }
            OutputStream out = new FileOutputStream(new File("D:\\Test\\C_IN0004_AppointmentLetter.pdf"));
            conversion.output(out, pdfSettings);
            System.out.println("DONE!!"); 
    }
}

0 个答案:

没有答案