Last active
December 14, 2015 00:29
-
-
Save jerryorr/4999571 to your computer and use it in GitHub Desktop.
Example of doc4jx PDF conversion losing text formatting (like bold)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.OutputStream; | |
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings; | |
import org.docx4j.fonts.BestMatchingMapper; | |
import org.docx4j.fonts.IdentityPlusMapper; | |
import org.docx4j.fonts.Mapper; | |
import org.docx4j.fonts.PhysicalFont; | |
import org.docx4j.fonts.PhysicalFonts; | |
import org.docx4j.jaxb.Context; | |
import org.docx4j.openpackaging.packages.WordprocessingMLPackage; | |
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; | |
import org.docx4j.wml.BooleanDefaultTrue; | |
import org.docx4j.wml.ObjectFactory; | |
import org.docx4j.wml.P; | |
import org.docx4j.wml.R; | |
import org.docx4j.wml.RPr; | |
import org.docx4j.wml.Text; | |
public class Docx4jFormatBug { | |
public static void main(String[] args) throws Exception { | |
WordprocessingMLPackage docPackage = WordprocessingMLPackage | |
.createPackage(); | |
MainDocumentPart document = docPackage.getMainDocumentPart(); | |
ObjectFactory factory = Context.getWmlObjectFactory(); | |
P para = factory.createP(); | |
// Add a bold run | |
Text boldText = factory.createText(); | |
boldText.setValue("This should be bold"); | |
R boldRun = factory.createR(); | |
boldRun.getContent().add(boldText); | |
RPr runProps = factory.createRPr(); | |
runProps.setB(new BooleanDefaultTrue()); | |
boldRun.setRPr(runProps); | |
para.getContent().add(boldRun); | |
// Add a plain-text run | |
Text plainText = factory.createText(); | |
plainText.setValue(", and this should be plain"); | |
R plainRun = factory.createR(); | |
plainRun.getContent().add(plainText); | |
para.getContent().add(plainRun); | |
document.addObject(para); | |
// Write as a docx; this works correctly | |
docPackage.save(new java.io.File("formatted_text_bug.docx")); | |
//Mapper fontMapper = new IdentityPlusMapper(); | |
Mapper fontMapper = new BestMatchingMapper(); | |
docPackage.setFontMapper(fontMapper); | |
PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Arial"); | |
fontMapper.getFontMappings().put("Calibri", font); | |
org.docx4j.convert.out.pdf.PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion( | |
docPackage); | |
// Convert to PDF and write; this has no formatting | |
OutputStream os = new java.io.FileOutputStream("formatted_text_bug.pdf"); | |
c.output(os, new PdfSettings()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment