org.docx4j.convert.out.FOSettings Java Examples

The following examples show how to use org.docx4j.convert.out.FOSettings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LayoutMasterSetBuilder.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
/**
    * For XSLFOExporterNonXSLT
    * @since 3.0
    * 
    */	
public static void appendLayoutMasterSetFragment(AbstractWmlConversionContext context, Node foRoot) {

	LayoutMasterSet lms = getFoLayoutMasterSet(context);	
	
	// Set suitable extents, for which we need area tree 
	FOSettings foSettings = (FOSettings)context.getConversionSettings();
	if ( !foSettings.lsLayoutMasterSetCalculationInProgress()) // Avoid infinite loop
		// Can't just do it where foSettings.getApacheFopMime() is not MimeConstants.MIME_FOP_AREA_TREE,
		// since TOC functionality uses that.
	{
		fixExtents( lms, context, false);
	}
	
	org.w3c.dom.Document document = XmlUtils.marshaltoW3CDomDocument(lms, Context.getXslFoContext() );
	XmlUtils.treeCopy(document.getDocumentElement(), foRoot);
}
 
Example #2
Source File: LayoutMasterSetBuilder.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
public static DocumentFragment getLayoutMasterSetFragment(AbstractWmlConversionContext context) {

		LayoutMasterSet lms = getFoLayoutMasterSet(context);	
		
		// Set suitable extents, for which we need area tree 
		FOSettings foSettings = (FOSettings)context.getConversionSettings();
		if ( !foSettings.lsLayoutMasterSetCalculationInProgress()) // Avoid infinite loop
			// Can't just do it where foSettings.getApacheFopMime() is not MimeConstants.MIME_FOP_AREA_TREE,
			// since TOC functionality uses that.
		{
			fixExtents( lms, context, true);
		}
		
		org.w3c.dom.Document document = XmlUtils.marshaltoW3CDomDocument(lms, Context.getXslFoContext() );
		DocumentFragment docfrag = document.createDocumentFragment();
		docfrag.appendChild(document.getDocumentElement());
		
		
		return docfrag;		
	}
 
Example #3
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a Fop configuration (unless FOSettings already has it)
 * based on fonts used in the document.
 * 
 * @param settings
 * @return
 * @throws Docx4JException
 */
private static String setupApacheFopConfiguration(FOSettings settings) throws Docx4JException {

	if (settings==null) throw new Docx4JException("FOSettings was null");
	String ret = settings.getApacheFopConfiguration();
	if (ret == null) {
		
		WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage)settings.getWmlPackage();
		if (wmlPackage==null) throw new Docx4JException("No WmlPackage in FOSettings");
		
		ret = FopConfigUtil.createDefaultConfiguration(wmlPackage.getFontMapper(), 
				wmlPackage.getMainDocumentPart().fontsInUse());
	}
	return ret;
}
 
Example #4
Source File: Conversion.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
protected void setupSettings(FOSettings settings, String mime) {
	if ((wordMLPackage != null) && (settings.getWmlPackage() == null)) {
		settings.setWmlPackage(wordMLPackage);
	}
	if ((saveFO != null) && (settings.getFoDumpFile() == null)) {
		settings.setFoDumpFile(saveFO);
	}
	settings.setApacheFopMime(mime);
}
 
Example #5
Source File: XSLFOExporterNonXSLT.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
public XSLFOExporterNonXSLT(WordprocessingMLPackage wmlPackage, 
		FOSettings  pdfSettings) {

	foSettings = pdfSettings;
	if ((foSettings.getWmlPackage() == null) && (wmlPackage != null)) {
		foSettings.setWmlPackage(wmlPackage);
	}
}
 
Example #6
Source File: AbstractFOExporter.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Override
protected FOConversionContext createContext(
		FOSettings conversionSettings, 
		WordprocessingMLPackage preprocessedPackage,
		ConversionSectionWrappers sectionWrappers) {
	return new FOConversionContext(conversionSettings, preprocessedPackage, sectionWrappers);
}
 
Example #7
Source File: TblHeaderTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
	 * "fo:table" content model is: (marker*,table-column*,table-header?,table-footer?,table-body+)
	 * 
	 * so a table with just a table header should have
	 * that converted to table-body row.
	 */
	@Test
	public  void testTblHeaderOne() throws Exception {
		
		String inputfilepath = System.getProperty("user.dir") + "/src/test/resources/tables/tblHeaderTestOne.docx";
		WordprocessingMLPackage wordMLPackage= WordprocessingMLPackage.load(new java.io.File(inputfilepath));	
		
    	FOSettings foSettings = Docx4J.createFOSettings();
		foSettings.setWmlPackage(wordMLPackage);
		
		// want the fo document as the result.
		foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
		
		// exporter writes to an OutputStream.		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    	

		//Don't care what type of exporter you use
//		Docx4J.toFO(foSettings, os, Docx4J.FLAG_NONE);
		//Prefer the exporter, that uses a xsl transformation
		Docx4J.toFO(foSettings, baos, Docx4J.FLAG_EXPORT_PREFER_XSL);

		byte[] bytes = baos.toByteArray();
//		System.out.println(new String(bytes, "UTF-8"));
	
		// Now use XPath to assert it has a table-body
		try {
			org.w3c.dom.Document domDoc = w3cDomDocumentFromByteArray( bytes);
			assertTrue(this.isAbsent(domDoc, "//fo:table-header"));
			assertTrue(this.isPresent(domDoc, "//fo:table-body"));
		} catch (SAXParseException e) {
			
			Assert.fail(e.getMessage());
			Assert.fail(new String(bytes, "UTF-8"));
		}
		
		
	}
 
Example #8
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
 * Allow user access to FOUserAgent, so they can setAccessibility(true).  Access to other settings
 * is possible but unsupported.
 * 
 * @param wmlPackage
 * @return
 * @throws FOPException
 */
public static FOUserAgent getFOUserAgent(FOSettings settings) throws Docx4JException, FOPException {
	
	FopFactory fopFactory = getFopFactory(
			setupApacheFopConfiguration(settings)); // relies on the WordML package being there, for font info
	settings.getSettings().put(FOP_FACTORY, fopFactory);
	
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
	settings.getSettings().put(FO_USER_AGENT, foUserAgent);
	
	return foUserAgent;
}
 
Example #9
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
private String setupApacheFopMime(FOSettings settings) {
String ret = settings.getApacheFopMime();
	if (ret == null) {
		ret = MimeConstants.MIME_PDF;
	}
	return ret;
}
 
Example #10
Source File: FOExporterVisitor.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
public static Exporter<FOSettings> getInstance() {
	if (instance == null) {
		synchronized(FOExporterVisitor.class) {
			if (instance == null) {
				instance = new FOExporterVisitor();
			}
		}
	}
	return instance;
}
 
Example #11
Source File: FOPAreaTreeHelper.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
static org.w3c.dom.Document getAreaTreeViaFOP(WordprocessingMLPackage hfPkg, boolean useXSLT) throws Docx4JException, ParserConfigurationException, SAXException, IOException  {

    	  // Currently FOP dependent!  But an Antenna House version ought to be feasible.
    	
        FOSettings foSettings = Docx4J.createFOSettings();
        foSettings.setWmlPackage(hfPkg);
        foSettings.setApacheFopMime(MimeConstants.MIME_FOP_AREA_TREE);
        
        foSettings.setLayoutMasterSetCalculationInProgress(true); // avoid recursion
        
//        foSettings.getFeatures().add(ConversionFeatures.PP_PDF_APACHEFOP_DISABLE_PAGEBREAK_LIST_ITEM); // in 3.0.1, this is off by default
        
        // Since hfPkg is already a clone, we don't need PP_COMMON_DEEP_COPY
        // Plus it invokes setFontMapper, which does processEmbeddings again, and those fonts aren't much use to us here
        foSettings.getFeatures().remove(ConversionFeatures.PP_COMMON_DEEP_COPY);
        
        if (log.isDebugEnabled()) {
        	foSettings.setFoDumpFile(new java.io.File(System.getProperty("user.dir") + "/hf.fo"));
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        if (useXSLT) {
        	Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
        } else {
        	Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);        	
        }
        
        InputStream is = new ByteArrayInputStream(os.toByteArray());
		DocumentBuilder builder = XmlUtils.getNewDocumentBuilder();
		return builder.parse(is);

    }
 
Example #12
Source File: FOExporterXslt.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
public static Exporter<FOSettings> getInstance() {
	if (instance == null) {
		synchronized(FOExporterXslt.class) {
			if (instance == null) {
				instance = new FOExporterXslt();
			}
		}
	}
	return instance;
}
 
Example #13
Source File: FOConversionContext.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
protected FORenderer initializeFoRenderer(FOSettings settings) {
	
	FORenderer ret = settings.getCustomFoRenderer();
	if (ret == null) {
		if (FOSettings.INTERNAL_FO_MIME.equals(settings.getApacheFopMime())) {
			ret = FORendererDummy.getInstance();
			forceRequires1Pass();
		}
		else {
			ret = FORendererApacheFOP.getInstance();
		}
		settings.setCustomFoRenderer(ret); // make sure this is always set
	}
	return ret;
}
 
Example #14
Source File: TblHeaderTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
	 * "fo:table" content model is: (marker*,table-column*,table-header?,table-footer?,table-body+)
	 * 
	 * so a table with body rows before header rows should have
	 * those body rows converted to header rows.
	 */
	@Test
	public  void testTblHeaderTwo() throws Exception {
		
		String inputfilepath = System.getProperty("user.dir") + "/src/test/resources/tables/tblHeaderTestTwo.docx";
		WordprocessingMLPackage wordMLPackage= WordprocessingMLPackage.load(new java.io.File(inputfilepath));	
		
    	FOSettings foSettings = Docx4J.createFOSettings();
		foSettings.setWmlPackage(wordMLPackage);
		
		// want the fo document as the result.
		foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
		
		// exporter writes to an OutputStream.		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    	

		//Don't care what type of exporter you use
//		Docx4J.toFO(foSettings, os, Docx4J.FLAG_NONE);
		//Prefer the exporter, that uses a xsl transformation
		Docx4J.toFO(foSettings, baos, Docx4J.FLAG_EXPORT_PREFER_XSL);

		byte[] bytes = baos.toByteArray();
//		System.out.println(new String(bytes, "UTF-8"));
	
		// Now use XPath to assert it has a table-body
		try {
			org.w3c.dom.Document domDoc = w3cDomDocumentFromByteArray( bytes);
			assertTrue(this.isAbsent(domDoc, "//fo:table-body[following-sibling::fo:table-header]"));
			assertTrue(this.isPresent(domDoc, "//fo:table-header[following-sibling::fo:table-body]"));
		} catch (SAXParseException e) {
			
			Assert.fail(e.getMessage());
			Assert.fail(new String(bytes, "UTF-8"));
		}
		
		
		
	}
 
Example #15
Source File: TextBoxTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
private static void execute(WordprocessingMLPackage wordMLPackage) throws Docx4JException, IOException {
	
   	// Pretty print the main document part
	System.out.println(
			XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true) );
	
	// Optionally save it
	if (save) {
		String filename = System.getProperty("user.dir") + "/OUT_CreateWordprocessingMLDocument.docx";
		wordMLPackage.save(new File(filename) );
		System.out.println("Saved " + filename);
	}
	
	// FO
	if (fo) {
		
		OutputStream baos = new ByteArrayOutputStream();
		Exporter<FOSettings> exporter = FOExporterVisitor.getInstance();
		FOSettings settings = new FOSettings();
		settings.setWmlPackage(wordMLPackage);
		settings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
		exporter.export(settings, baos);
		
		System.out.println( ((ByteArrayOutputStream) baos).toString("UTF-8"));
		
	} else {
		
		Docx4J.toPDF(wordMLPackage, 
				FileUtils.openOutputStream(new File(System.getProperty("user.dir") + "/OUT_textbox.pdf")));
		
	}		
}
 
Example #16
Source File: AbstractFOExporter.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
protected AbstractFOExporter(AbstractExporterDelegate<FOSettings, FOConversionContext> exporterDelegate) {
	super(exporterDelegate);
}
 
Example #17
Source File: FONonXSLT.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		String inputfilepath;	
		String outputfilepath;		

		inputfilepath = System.getProperty("user.dir")
//				+ "/hlink.docx";
//		+ "/OpenXML_1ed_Part4.docx";
//		+ "/sample-docs/word/sample-docx.docx";
//		+ "/sample-docs/word/2003/word2003-vml.docx";
//				+ "/table-nested.docx";
//		+ "/sample-docs/word/headers.docx";
		+ "/sample-docs/word/sample-docxv2.docx";		
		
		WordprocessingMLPackage wmlPackage = WordprocessingMLPackage
				.load(new java.io.File(inputfilepath));
		
		FOSettings pdfSettings = new FOSettings();
		pdfSettings.setWmlPackage(wmlPackage);
		
		
		XSLFOExporterNonXSLT withoutXSLT = new XSLFOExporterNonXSLT(wmlPackage, 
				pdfSettings);		
//		new PDFConversionImageHandler(settings.getImageDirPath(), true) : 
//				new HTMLConversionImageHandler("c:\\temp", "/bar", true) );
		

		
		long startTime = System.currentTimeMillis();				
		Document xslfo = withoutXSLT.export();
		long endTime = System.currentTimeMillis();
		System.out.println("done.  elapsed time: " + Math.round((endTime-startTime)/1000) );

		System.out.println(XmlUtils.w3CDomNodeToString(xslfo));
		
		
		outputfilepath = inputfilepath + "K.pdf";
		OutputStream os = new java.io.FileOutputStream(outputfilepath);
		
		// OK, do it...
		withoutXSLT.output(xslfo, os, null);
		System.out.println("Saved " + outputfilepath);	
	}
 
Example #18
Source File: Conversion.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
public void outputXSLFO(OutputStream os, PdfSettings settings) throws Docx4JException {
	setupSettings(settings, FOSettings.MIME_PDF);
	Docx4J.toFO(settings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
}
 
Example #19
Source File: Docx4jUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public static void toP(WordprocessingMLPackage wordMLPackage,String outPath) throws Exception{
    OutputStream os = new FileOutputStream(outPath);
    FOSettings foSettings = Docx4J.createFOSettings();
    foSettings.setWmlPackage(wordMLPackage);
    Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
}
 
Example #20
Source File: FOConversionContext.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
public FOConversionContext(FOSettings settings, WordprocessingMLPackage wmlPackage, ConversionSectionWrappers conversionSectionWrappers) {
	super(FO_WRITER_REGISTRY, FO_MESSAGE_WRITER, settings, wmlPackage, conversionSectionWrappers, createRunFontSelector(wmlPackage));
	this.foRenderer = initializeFoRenderer(settings);
}
 
Example #21
Source File: WordToPdfRenditionProvider.java    From spring-content with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
	try {
		// Font regex (optional)
		// Set regex if you want to restrict to some defined subset of fonts
		// Here we have to do this before calling createContent,
		// since that discovers fonts
		String regex = null;
		// Windows:
		// String
		// regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
		// regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
		// Mac
		// String
		// regex=".*(Courier New|Arial|Times New Roman|Comic
		// Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino
		// Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans
		// Serif|MS Serif).*";
		PhysicalFonts.setRegex(regex);

		WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource);

		// Refresh the values of DOCPROPERTY fields
		FieldUpdater updater = new FieldUpdater(pkg);
		updater.update(true);

		// FO exporter setup (required)
		// .. the FOSettings object
		FOSettings foSettings = Docx4J.createFOSettings();
		// if (false) {
		// foSettings.setFoDumpFile(new java.io.File("/tmp/test.fo"));
		// }
		foSettings.setWmlPackage(pkg);

		// ByteArrayOutputStream os = new ByteArrayOutputStream();

		String outputfilepath;
		outputfilepath = "/tmp/temp.pdf";
		OutputStream os = new java.io.FileOutputStream(outputfilepath);

		// Specify whether PDF export uses XSLT or not to create the FO
		// (XSLT takes longer, but is more complete).

		// Don't care what type of exporter you use
		Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

		if (pkg.getMainDocumentPart().getFontTablePart() != null) {
			pkg.getMainDocumentPart().getFontTablePart()
					.deleteEmbeddedFontTempFiles();
		}

		return new FileInputStream(outputfilepath);
	}
	catch (Exception e) {

	}

	return null;
}
 
Example #22
Source File: WordprocessingMLPackageWriter.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
 * @param wmlPackage {@link WordprocessingMLPackage} 对象
 * @param output 文件输出流
 * @throws IOException :IO异常
 * @throws Docx4JException : Docx4j异常
 */
public void writeToPDFWhithFo(WordprocessingMLPackage wmlPackage, OutputStream output) throws IOException, Docx4JException {
	Assert.notNull(wmlPackage, " wmlPackage is not specified!");
	Assert.notNull(output, " output is not specified!");
       try {
       	
		// Font regex (optional)
		// Set regex if you want to restrict to some defined subset of fonts
		// Here we have to do this before calling createContent,
		// since that discovers fonts
		//String regex = null;
		
		// Refresh the values of DOCPROPERTY fields 
		FieldUpdater updater = new FieldUpdater(wmlPackage);
		updater.update(true);
		
		// .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
		// eg Glyph "ي" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
		// eg Glyph "ج" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
		// to a font which does
		PhysicalFonts.get("Arial Unicode MS"); 

		// FO exporter setup (required)
		// .. the FOSettings object
	    FOSettings foSettings = Docx4J.createFOSettings();
	    
		foSettings.setWmlPackage(wmlPackage);
        foSettings.setApacheFopMime("application/pdf");
            
		// Document format: 
		// The default implementation of the FORenderer that uses Apache Fop will output
		// a PDF document if nothing is passed via 
		// foSettings.setApacheFopMime(apacheFopMime)
		// apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
		// FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
		//foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
		
		// Specify whether PDF export uses XSLT or not to create the FO
		// (XSLT takes longer, but is more complete).
		
		// Don't care what type of exporter you use
		Docx4J.toFO(foSettings, output, Docx4J.FLAG_EXPORT_PREFER_XSL);
		
		// Prefer the exporter, that uses a xsl transformation
		// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
		
		// Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
		// faster, but not yet at feature parity
		// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);
		   
		// Clean up, so any ObfuscatedFontPart temp files can be deleted 
		// if (wordMLPackage.getMainDocumentPart().getFontTablePart()!=null) {
		// 	wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
		// } 
		// This would also do it, via finalize() methods
		updater = null;
		foSettings = null;
		wmlPackage = null;
	} finally{
		IOUtils.closeQuietly(output);
       }
}
 
Example #23
Source File: Conversion.java    From docx4j-export-FO with Apache License 2.0 2 votes vote down vote up
/** Create a pdf version of the document, using XSL FO. 
 * 
 * @param os
 *            The OutputStream to write the pdf to 
 * @param settings
 *            The configuration for the conversion 
 * 
 * */     
public void output(OutputStream os, PdfSettings settings) throws Docx4JException {
	setupSettings(settings, FOSettings.INTERNAL_FO_MIME);
	Docx4J.toPDF(wordMLPackage, os);
}