org.docx4j.fonts.PhysicalFonts Java Examples

The following examples show how to use org.docx4j.fonts.PhysicalFonts. 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: HtmlConverter.java    From docx4j-template with Apache License 2.0 7 votes vote down vote up
/**
 * 为 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 配置中文字体
 *
 * @param wordMLPackage
 * @throws Exception
 */
protected void configSimSunFont(WordprocessingMLPackage wordMLPackage) throws Exception {
    Mapper fontMapper = new IdentityPlusMapper();
    wordMLPackage.setFontMapper(fontMapper);

    String fontFamily = "SimSun";

    URL simsunUrl = this.getClass().getResource("/org/noahx/html2docx/simsun.ttc"); //加载字体文件(解决linux环境下无中文字体问题)
    PhysicalFonts.addPhysicalFonts(fontFamily, simsunUrl);
    PhysicalFont simsunFont = PhysicalFonts.get(fontFamily);
    fontMapper.put(fontFamily, simsunFont);

    RFonts rfonts = Context.getWmlObjectFactory().createRFonts(); //设置文件默认字体
    rfonts.setAsciiTheme(null);
    rfonts.setAscii(fontFamily);
    wordMLPackage.getMainDocumentPart().getPropertyResolver()
            .getDocumentDefaultRPr().setRFonts(rfonts);
}
 
Example #2
Source File: PhysicalFontUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public static void setPhysicalFont(WordprocessingMLPackage wmlPackage,String fontName) throws Exception {
//Mapper fontMapper = new BestMatchingMapper();  
Mapper fontMapper = wmlPackage.getFontMapper() == null ? new IdentityPlusMapper() : wmlPackage.getFontMapper();
//获取字体库
PhysicalFont physicalFont = PhysicalFonts.get(fontName);
//分别设置字体名和别名对应的字体库
fontMapper.put(fontName, physicalFont );
//设置文档字体库
wmlPackage.setFontMapper(fontMapper, true);
  }
 
Example #3
Source File: SampleDocument.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public static void createContent(MainDocumentPart wordDocumentPart ) {
	/*
	 * NB, this currently works nicely with
	 * viaIText, and viaXSLFO (provided
	 * you view with Acrobat Reader .. it 
	 * seems to overwhelm pdfviewer, which
	 * is weird, since viaIText works in both).
	 */
	
	try {
		// Do this explicitly, since we need
		// it in order to create our content
		PhysicalFonts.discoverPhysicalFonts(); 						
														
		Map<String, PhysicalFont> physicalFontMap = PhysicalFonts.getPhysicalFonts();			
		Iterator physicalFontMapIterator = physicalFontMap.entrySet().iterator();
		while (physicalFontMapIterator.hasNext()) {
		    Map.Entry pairs = (Map.Entry)physicalFontMapIterator.next();
		    if(pairs.getKey()==null) {
		    	pairs = (Map.Entry)physicalFontMapIterator.next();
		    }
		    String fontName = (String)pairs.getKey();
		    PhysicalFont pf = (PhysicalFont)pairs.getValue();
		    
		    System.out.println("Added paragraph for " + fontName);
		    addObject(wordDocumentPart, sampleText, fontName );

		    // bold, italic etc
		    PhysicalFont pfVariation = PhysicalFonts.getBoldForm(pf);
		    if (pfVariation!=null) {
			    addObject(wordDocumentPart, sampleTextBold, pfVariation.getName() );
		    }
		    pfVariation = PhysicalFonts.getBoldItalicForm(pf);
		    if (pfVariation!=null) {
			    addObject(wordDocumentPart, sampleTextBoldItalic, pfVariation.getName() );
		    }
		    pfVariation = PhysicalFonts.getItalicForm(pf);
		    if (pfVariation!=null) {
			    addObject(wordDocumentPart, sampleTextItalic, pfVariation.getName() );
		    }
		    
		}
	} catch (Exception e) {
		e.printStackTrace();
	}    		    
	
}
 
Example #4
Source File: PhysicalFontUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
private static Mapper newFontMapper() throws Exception {
	
	// Set up font mapper (optional)
	
	//  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"); 
	
	
	/*
	 * This mapper uses Panose to guess the physical font which is a closest fit for the font used in the document.
	 * (这个映射器使用Panose算法猜测最适合这个文档使用的物理字体。)
	 * 
	 * Panose是一种依照字体外观来进行分类的方法。我们可以通过PANOSE体系将字体的外观特征进行整理,并且与其它字体归类比较。
	 * Panose的原形在1985年由Benjamin Bauermeister开发,当时一种字体由7位16进制数字定义,现在则发展为10位,也就是字体的十种特征。这每一位数字都给出了它定义的一种视觉外观的量度,如笔划的粗细或是字体衬线的样式等。
	 * Panose定义的范围:Latin Text,Latin Script,Latin Decorative,Iconographic,Japanese Text,Cyrillic Text,Hebrew。
	 * 	
	 * It is most likely to be suitable on Linux or OSX systems which don't have Microsoft's fonts installed.
	 * (它很可能适用于没有安装Microsoft字体的Linux或OSX系统。)
	 * 
	 * 1、获取Microsoft字体我们需要这些:a.在Microsoft平台上,嵌入PDF输出; b. docx4all - 所有平台 - 填充字体下拉列表
	 * setupMicrosoftFontFilenames();
	 * 2、 自动检测系统上可用的字体
	 * PhysicalFonts.discoverPhysicalFonts();
	 * 
	 */
	//Mapper fontMapper = new BestMatchingMapper();  
	/*
	 * 
	 * This mapper automatically maps document fonts for which the exact font is physically available.  
     * Think of this as an identity mapping.  For  this reason, it will work best on Windows, or a system on 
     * which Microsoft fonts have been installed.
     * (此映射器自动映射确切可用的文档字体,将此视为标识映射;基于这个原因,它在Windows系统或安装了微软字体库的系统运行的更好。)
     * You can manually add your own additional mappings if you wish.
     * 如果需要,你可以手动添加自己的字体映射
	 * 
	 * 1、 自动检测系统上可用的字体
	 * PhysicalFonts.discoverPhysicalFonts();
	 * 
	 */
	Mapper fontMapper = new IdentityPlusMapper();
	//进行中文字体兼容处理
	fontMapper.put("微软雅黑",PhysicalFonts.get("Microsoft Yahei"));
       fontMapper.put("黑体",PhysicalFonts.get("SimHei"));
       fontMapper.put("楷体",PhysicalFonts.get("KaiTi"));
       fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
       fontMapper.put("宋体",PhysicalFonts.get("SimSun"));
       fontMapper.put("宋体扩展",PhysicalFonts.get("simsun-extB"));
       fontMapper.put("新宋体",PhysicalFonts.get("NSimSun"));
       fontMapper.put("仿宋",PhysicalFonts.get("FangSong"));
       fontMapper.put("仿宋_GB2312",PhysicalFonts.get("FangSong_GB2312"));
       fontMapper.put("幼圆",PhysicalFonts.get("YouYuan"));
       fontMapper.put("华文宋体",PhysicalFonts.get("STSong"));
       fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
       fontMapper.put("华文中宋",PhysicalFonts.get("STZhongsong"));
       fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
       
       return fontMapper;
}
 
Example #5
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 #6
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 #7
Source File: Conversion.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
/** Create a pdf version of the document. 
	 * 
	 * @param os
	 *            The OutputStream to write the pdf to 
	 * 
	 * */     
    public void output(OutputStream os) throws Docx4JException {
    	
    					
        try {
			// Put the html in result
			org.w3c.dom.Document xhtmlDoc = org.docx4j.XmlUtils.neww3cDomDocument();
			javax.xml.transform.dom.DOMResult result = new javax.xml.transform.dom.DOMResult(xhtmlDoc);
			
			AbstractHtmlExporter exporter = new HtmlExporter();
			exporter.html(wordMLPackage, result, false,
					System.getProperty("java.io.tmpdir") ); // false -> don't use HTML fonts.
					
			// Now render the XHTML
			org.xhtmlrenderer.pdf.ITextRenderer renderer = new org.xhtmlrenderer.pdf.ITextRenderer();
					
			// 4.  Use addFont code like that below as necessary for the fonts
			
				// See https://xhtmlrenderer.dev.java.net/guide/users-guide-r7.html#xil_32
			org.xhtmlrenderer.extend.FontResolver resolver = renderer.getFontResolver();		
					
			Map fontsInUse = wordMLPackage.getMainDocumentPart().fontsInUse();
			Iterator fontMappingsIterator = fontsInUse.entrySet().iterator();
			while (fontMappingsIterator.hasNext()) {
			    Map.Entry pairs = (Map.Entry)fontMappingsIterator.next();
			    if(pairs.getKey()==null) {
			    	log.info("Skipped null key");
			    	pairs = (Map.Entry)fontMappingsIterator.next();
			    }
			    
			    String fontName = (String)pairs.getKey();
			    
			    PhysicalFont pf = wordMLPackage.getFontMapper().getFontMappings().get(fontName);
			    
			    if (pf==null) {
			    	log.error("Document font " + fontName + " is not mapped to a physical font!");
			    	continue;
			    }
			    
			    embed(renderer, pf);	        
			    // For any font we embed, also embed the bold, italic, and bold italic substitute
			    // .. at present, we can't tell which of these forms are actually used, so add them all
			    // bold, italic etc
			    PhysicalFont pfVariation = PhysicalFonts.getBoldForm(pf);
			    if (pfVariation!=null) {
				    embed(renderer, pfVariation);	        
			    }
			    pfVariation = PhysicalFonts.getBoldItalicForm(pf);
			    if (pfVariation!=null) {
				    embed(renderer, pfVariation);	        
			    }
			    pfVariation = PhysicalFonts.getItalicForm(pf);
			    if (pfVariation!=null) {
				    embed(renderer, pfVariation);	        
			    }
			    
			}
			
			// TESTING
//	    xhtmlDoc = org.docx4j.XmlUtils.neww3cDomDocument();
//	    try {
//			xhtmlDoc = XmlUtils.getNewDocumentBuilder().parse(new File("C:\\Users\\jharrop\\workspace\\docx4all\\sample-docs\\comic.html"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        } 	    
			
			renderer.setDocument(xhtmlDoc, null);
			renderer.layout();
			
			renderer.createPDF(os);
		} catch (Exception e) {
			throw new Docx4JException("Failed creating PDF via HTML " ,e);
		}
		
		
	}
 
Example #8
Source File: SampleDocumentGenerator.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
public static void createContent(MainDocumentPart wordDocumentPart ) {
	/*
	 * NB, this currently works nicely with
	 * viaIText, and viaXSLFO (provided
	 * you view with Acrobat Reader .. it 
	 * seems to overwhelm pdfviewer, which
	 * is weird, since viaIText works in both).
	 */
	
	try {
		// Do this explicitly, since we need
		// it in order to create our content
		PhysicalFonts.discoverPhysicalFonts(); 						
														
		Map<String, PhysicalFont> physicalFontMap = PhysicalFonts.getPhysicalFonts();			
		Iterator physicalFontMapIterator = physicalFontMap.entrySet().iterator();
		while (physicalFontMapIterator.hasNext()) {
		    Map.Entry pairs = (Map.Entry)physicalFontMapIterator.next();
		    if(pairs.getKey()==null) {
		    	pairs = (Map.Entry)physicalFontMapIterator.next();
		    }
		    String fontName = (String)pairs.getKey();
		    PhysicalFont pf = (PhysicalFont)pairs.getValue();
		    
		    System.out.println("Added paragraph for " + fontName);
		    addObject(wordDocumentPart, sampleText, fontName );

		    // bold, italic etc
		    PhysicalFont pfVariation = PhysicalFonts.getBoldForm(pf);
		    if (pfVariation!=null) {
			    addObject(wordDocumentPart, sampleTextBold, pfVariation.getName() );
		    }
		    pfVariation = PhysicalFonts.getBoldItalicForm(pf);
		    if (pfVariation!=null) {
			    addObject(wordDocumentPart, sampleTextBoldItalic, pfVariation.getName() );
		    }
		    pfVariation = PhysicalFonts.getItalicForm(pf);
		    if (pfVariation!=null) {
			    addObject(wordDocumentPart, sampleTextItalic, pfVariation.getName() );
		    }
		    
		}
	} catch (Exception e) {
		e.printStackTrace();
	}    		    
	
}
 
Example #9
Source File: Fonts.java    From docx4j-template with Apache License 2.0 2 votes vote down vote up
@Test
public void listFonts() throws Exception {
	
	PhysicalFonts.discoverPhysicalFonts();
	
}
 
Example #10
Source File: TextBoxTest.java    From docx4j-export-FO with Apache License 2.0 2 votes vote down vote up
private static WordprocessingMLPackage createTextBoxDocx(boolean w10WrapEl, String style) throws InvalidFormatException {
		
		// speedup
//		String regex = ".*(calibri|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
		String regex = ".*(calibri|cour|arial).*";
		PhysicalFonts.setRegex(regex);		

		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
		
	    P p = new P();
	    mdp.getContent().add(p);
	    
	    R r = Context.getWmlObjectFactory().createR(); 
	    
	    r.getContent().add(
	    		
	    		// Absolute position to the right of column produces:

				// margin-left:108pt
				// mso-position-horizontal:absolute <------------
				// mso-position-horizontal-relative:text
		    	// mso-wrap-style:square

		// style="position:absolute;margin-left:108pt;margin-top:0;width:186.95pt;height:110.55pt;z-index:251659264;visibility:visible;mso-wrap-style:square;mso-width-percent:400;mso-height-percent:200;mso-wrap-distance-left:9pt;mso-wrap-distance-top:0;mso-wrap-distance-right:9pt;mso-wrap-distance-bottom:0;mso-position-horizontal:absolute;mso-position-horizontal-relative:text;mso-position-vertical:absolute;mso-position-vertical-relative:text;mso-width-percent:400;mso-height-percent:200;mso-width-relative:margin;mso-height-relative:margin;v-text-anchor:top" 
	    		createPict(w10WrapEl, style,
	    				createContent("text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content text box content ")));

	    
	    
	    		// Relative position is done in percentages..

				//  mso-left-percent:600
				//  mso-position-horizontal-relative:left-margin-area
				//  mso-width-relative:margin
	    
//	    style="position:absolute;margin-left:0;margin-top:0;width:186.95pt;height:110.55pt;z-index:251659264;visibility:visible;mso-wrap-style:square;mso-width-percent:400;mso-height-percent:200;mso-left-percent:600;mso-wrap-distance-left:9pt;mso-wrap-distance-top:0;mso-wrap-distance-right:9pt;mso-wrap-distance-bottom:0;mso-position-horizontal-relative:left-margin-area;mso-position-vertical:absolute;mso-position-vertical-relative:text;mso-width-percent:400;mso-height-percent:200;mso-left-percent:600;mso-width-relative:margin;mso-height-relative:margin;v-text-anchor:top" 
	    

	    
	    p.getContent().add( r); 
	    
	    p.getContent().add(addFiller());
	    
	    return wordMLPackage;
		
	}