Created
February 21, 2013 20:50
-
-
Save jerryorr/5008120 to your computer and use it in GitHub Desktop.
Working version of https://gist.github.com/jerryorr/4999571
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
package orr.export; | |
import java.io.OutputStream; | |
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings; | |
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.RFonts; | |
import org.docx4j.wml.RPr; | |
import org.docx4j.wml.Styles; | |
import org.docx4j.wml.Text; | |
public class Docx4jFormatBugFixed { | |
public static void main(String[] args) throws Exception { | |
ObjectFactory factory = Context.getWmlObjectFactory(); | |
WordprocessingMLPackage docPackage = WordprocessingMLPackage | |
.createPackage(); | |
MainDocumentPart document = docPackage.getMainDocumentPart(); | |
// Convert all styles to use a font that I know is on my system | |
Styles styles = document.getStyleDefinitionsPart().getJaxbElement(); | |
for (org.docx4j.wml.Style s : styles.getStyle()) { | |
RPr rPr = s.getRPr(); | |
if (rPr == null) { | |
rPr = factory.createRPr(); | |
s.setRPr(rPr); | |
} | |
RFonts rf = rPr.getRFonts(); | |
if (rf == null) { | |
rf = factory.createRFonts(); | |
rPr.setRFonts(rf); | |
} | |
rf.setAscii("Arial"); | |
} | |
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 | |
docPackage.save(new java.io.File("formatted_text.docx")); | |
// Convert to PDF and write | |
org.docx4j.convert.out.pdf.PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion( | |
docPackage); | |
OutputStream os = new java.io.FileOutputStream("formatted_text.pdf"); | |
c.output(os, new PdfSettings()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment