com.lowagie.text.pdf.BaseFont Java Examples

The following examples show how to use com.lowagie.text.pdf.BaseFont. 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: BaseFontSupport.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private String getFontName( final BaseFont font ) {
  final String[][] names = font.getFullFontName();
  final int nameCount = names.length;
  if ( nameCount == 1 ) {
    return names[ 0 ][ 3 ];
  }

  String nameExtr = null;
  for ( int k = 0; k < nameCount; ++k ) {
    final String[] name = names[ k ];
    // Macintosh language english
    if ( "1".equals( name[ 0 ] ) && "0".equals( name[ 1 ] ) ) {
      nameExtr = name[ 3 ];
    }
    // Microsoft language code for US-English ...
    else if ( "1033".equals( name[ 2 ] ) ) {
      nameExtr = name[ 3 ];
      break;
    }
  }

  if ( nameExtr != null ) {
    return nameExtr;
  }
  return names[ 0 ][ 3 ];
}
 
Example #2
Source File: ListEncodingsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Listing the encodings of font comic.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {

	File font = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
	BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "encodings.txt"));
	BaseFont bfComic = BaseFont.createFont(font.getAbsolutePath(), BaseFont.CP1252,
			BaseFont.NOT_EMBEDDED);
	out.write("postscriptname: " + bfComic.getPostscriptFontName());
	out.write("\r\n\r\n");
	String[] codePages = bfComic.getCodePagesSupported();
	out.write("All available encodings:\n\n");
	for (int i = 0; i < codePages.length; i++) {
		out.write(codePages[i]);
		out.write("\r\n");
	}
	out.flush();
	out.close();

}
 
Example #3
Source File: TrueTypeTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Using a True Type Font.
 */
@Test
public void main() throws Exception {


	// step 1: creation of a document-object
	Document document = new Document();

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file
	PdfWriter.getInstance(document,PdfTestBase.getOutputStream("truetype.pdf"));

	// step 3: we open the document
	document.open();

	String f = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf").getAbsolutePath();
	// step 4: we add content to the document
	BaseFont bfComic = BaseFont.createFont(f, BaseFont.CP1252,	BaseFont.NOT_EMBEDDED);
	Font font = new Font(bfComic, 12);
	String text1 = "This is the quite popular Liberation Mono.";
	document.add(new Paragraph(text1, font));

	// step 5: we close the document
	document.close();
}
 
Example #4
Source File: BaseFontRecord.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates a new font record.
 *
 * @param fileName the physical filename name of the font file.
 * @param embedded a flag that defines whether this font should be embedded in the target document.
 * @param baseFont the generated base font for the given font definition.
 */
public BaseFontRecord( final String fileName,
                       final boolean trueTypeFont,
                       final boolean embedded,
                       final BaseFont baseFont,
                       final boolean bold,
                       final boolean italics ) {
  if ( baseFont == null ) {
    throw new NullPointerException( "iText-FontDefinition is null." );
  }
  if ( fileName == null ) {
    throw new NullPointerException( "Logical font name is null." );
  }
  this.trueTypeFont = trueTypeFont;
  this.baseFont = baseFont;
  this.fileName = fileName;
  this.embedded = embedded;
  this.italics = italics;
  this.bold = bold;
}
 
Example #5
Source File: BulkReceivingPdf.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable and set its logo image if 
 * there is a logoImage to be used, creates and sets the nestedHeaderTable and its content.
 * 
 * @param writer    The PdfWriter for this document.
 * @param document  The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {
        
        loadHeaderTable();
        
        // initialization of the template
        tpl = writer.getDirectContent().createTemplate(100, 100);
        
        // initialization of the font
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
        
    }catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #6
Source File: ITextDSSNativeFontTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	documentToSign = new InMemoryDocument(getClass().getResourceAsStream("/sample.pdf"));

	signatureParameters = new PAdESSignatureParameters();
	signatureParameters.bLevel().setSigningDate(new Date());
	signatureParameters.setSigningCertificate(getSigningCert());
	signatureParameters.setCertificateChain(getCertificateChain());
	signatureParameters.setSignatureLevel(SignatureLevel.PAdES_BASELINE_B);
	
	SignatureImageParameters signatureImageParameters = new SignatureImageParameters();
	
	SignatureImageTextParameters textParameters = new SignatureImageTextParameters();
	textParameters.setText("My signature\nOne more line\nAnd the last line");
	textParameters.setTextColor(Color.BLUE);
	textParameters.setBackgroundColor(Color.YELLOW);
	textParameters.setSignerTextHorizontalAlignment(SignerTextHorizontalAlignment.CENTER);
	
	BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
	textParameters.setFont(new ITextNativeFont(baseFont));
	
	signatureImageParameters.setTextParameters(textParameters);
	signatureParameters.setImageParameters(signatureImageParameters);

	service = new PAdESService(getOfflineCertificateVerifier());
}
 
Example #7
Source File: FullFontNamesTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Retrieving the full font name
 */
@Test
public void main() throws Exception {

	
	File font = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
	BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR
			+ "fullfontname_liberationmono.txt"));
	BaseFont bf = BaseFont.createFont(font.getAbsolutePath(), "winansi", BaseFont.NOT_EMBEDDED);
	out.write("postscriptname: " + bf.getPostscriptFontName());
	out.write("\r\n\r\n");
	String names[][] = bf.getFullFontName();
	out.write("\n\nListing the full font name:\n\n");
	for (int k = 0; k < names.length; ++k) {
		if (names[k][0].equals("3") && names[k][1].equals("1")) {
			 // Microsoftencoding
			out.write(names[k][3] + "\r\n");
		}
	}
	out.flush();
	out.close();

}
 
Example #8
Source File: TextOnlySignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private BaseFont getBaseFont(DSSFont dssFont) {
	if (dssFont instanceof ITextNativeFont) {
		ITextNativeFont nativeFont = (ITextNativeFont) dssFont;
		return nativeFont.getFont();
	} else if (dssFont instanceof DSSFileFont) {
		DSSFileFont fileFont = (DSSFileFont) dssFont;
		try (InputStream iStream = fileFont.getInputStream()) {
			byte[] fontBytes = DSSUtils.toByteArray(iStream);
			BaseFont baseFont = BaseFont.createFont(fileFont.getName(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, fontBytes, null);
			baseFont.setSubset(false);
			return baseFont;
		} catch (IOException e) {
			throw new DSSException("The iText font cannot be initialized", e);
		}
	} else {
		DefaultFontMapper fontMapper = new DefaultFontMapper();
		return fontMapper.awtToPdf(dssFont.getJavaFont());
	}
}
 
Example #9
Source File: OpenTypeFontTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Using oth
 */
@Test
public void main() throws Exception {
	// step 1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step 2
	PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("opentypefont.pdf"));
	// step 3
	document.open();
	// step 4
	BaseFont bf = BaseFont.createFont(PdfTestBase.RESOURCES_DIR
			+ "liz.otf", BaseFont.CP1252, true);
	String text = "Some text with the otf font LIZ.";
	document.add(new Paragraph(text, new Font(bf, 14)));
	// step 5
	document.close();
}
 
Example #10
Source File: cfDOCUMENT.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private void resolveFonts( cfSession _Session, ITextRenderer _renderer ) throws dataNotSupportedException, cfmRunTimeException{
	ITextFontResolver resolver = _renderer.getFontResolver();
	
	boolean embed = getDynamic( _Session, "FONTEMBED" ).getBoolean();
	for ( int i = 0; i < defaultFontDirs.length; i++ ){
		File nextFontDir = new File( defaultFontDirs[i] );
		File[] fontFiles = nextFontDir.listFiles( new FilenameFilter() {
			public boolean accept( File _dir, String _name ){
				String name = _name.toLowerCase();
				return name.endsWith( ".otf" ) || name.endsWith( ".ttf" );
			}
     });
		if ( fontFiles != null ){
      for ( int f = 0; f < fontFiles.length; f++ ){
      	try{
      		resolver.addFont( fontFiles[f].getAbsolutePath(), BaseFont.IDENTITY_H,
  	          embed );
      	}catch( Exception ignored ){} // ignore fonts that can't be added
      }
		}
	}
}
 
Example #11
Source File: PdfContext.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Return the text box for the specified text and font.
 *
 * @param text text
 * @param font font
 * @return text box
 */
public Rectangle getTextSize(String text, Font font) {
	template.saveState();
	// get the font
	DefaultFontMapper mapper = new DefaultFontMapper();
	BaseFont bf = mapper.awtToPdf(font);
	template.setFontAndSize(bf, font.getSize());
	// calculate text width and height
	float textWidth = template.getEffectiveStringWidth(text, false);
	float ascent = bf.getAscentPoint(text, font.getSize());
	float descent = bf.getDescentPoint(text, font.getSize());
	float textHeight = ascent - descent;
	template.restoreState();
	return new Rectangle(0, 0, textWidth, textHeight);
}
 
Example #12
Source File: PdfTimetableGridTable.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void addTextVertical(PdfPCell cell, String text, boolean bold) throws Exception  {
	if (text==null) return;
       if (text.indexOf("<span")>=0)
           text = text.replaceAll("</span>","").replaceAll("<span .*>", "");
       Font font = PdfFont.getFont(bold);
	BaseFont bf = font.getBaseFont();
	float width = bf.getWidthPoint(text, font.getSize());
	PdfTemplate template = iWriter.getDirectContent().createTemplate(2 * font.getSize() + 4, width);
	template.beginText();
	template.setColorFill(Color.BLACK);
	template.setFontAndSize(bf, font.getSize());
	template.setTextMatrix(0, 2);
	template.showText(text);
	template.endText();
	template.setWidth(width);
	template.setHeight(font.getSize() + 2);
	//make an Image object from the template
	Image img = Image.getInstance(template);
	img.setRotationDegrees(270);
	//embed the image in a Chunk
	Chunk ck = new Chunk(img, 0, 0);
	
	if (cell.getPhrase()==null) {
		cell.setPhrase(new Paragraph(ck));
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
	} else {
		cell.getPhrase().add(ck);
	}
}
 
Example #13
Source File: FontCreator.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private Font createInitialFont() {
    try {
        ClassPathResource resource = new ClassPathResource("fonts/" + FONT_NAME);
        byte[] bytes = IOUtils.toByteArray(resource.getInputStream());
        BaseFont baseFont = BaseFont.createFont(FONT_NAME, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, bytes, null);
        return new Font(baseFont, 12);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #14
Source File: AdvancedPageNumberEvents.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * we override the onOpenDocument method.
 *
 * @param writer
 *           PdfWriter
 * @param document
 *           Document
 */
@Override
public void onOpenDocument(final PdfWriter writer, final Document document) {
	try {
		bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
		cb = writer.getDirectContent();
		template = cb.createTemplate(50, 50);
	} catch (final DocumentException de) {
		throw new IllegalStateException(de);
	} catch (final IOException ioe) {
		throw new IllegalStateException(ioe);
	}
}
 
Example #15
Source File: JasperReportsUtil.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static byte[] getBytes(JRAbstractExporter exporter, ByteArrayOutputStream baos,
                                  JasperPrint jasperPrint) throws JRException {

       printNextReportsParameters();

       // for csv delimiter
       //exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, ";");
       exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
       exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);

       if (exporter instanceof JRPdfExporter) {
           exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, encoding);

           // create embedded pdf font (like in nextreports)
           if (embeddedFont != null) {
               HashMap<FontKey, PdfFont> fontMap = new HashMap<FontKey, PdfFont>();
               FontKey key = new FontKey("Arial", false, false);
               PdfFont font = new PdfFont(embeddedFont, BaseFont.IDENTITY_H, true);
               fontMap.put(key, font);
               exporter.setParameter(JRPdfExporterParameter.FONT_MAP, fontMap);
           }
       } else {
           exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
       }

       exporter.exportReport();
       return baos.toByteArray();
   }
 
Example #16
Source File: FontHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * If the BaseFont can NOT find the correct physical glyph, we need to
 * simulate the proper style for the font. The "simulate" flag will be set
 * if we need to simulate it.
 */
private boolean needSimulate( BaseFont font )
{
	if ( fontStyle == Font.NORMAL )
	{
		return false;
	}

	String[][] fullNames = bf.getFullFontName( );
	String fullName = getEnglishName( fullNames );
	String lcf = fullName.toLowerCase( );

	int fs = Font.NORMAL;
	if ( lcf.indexOf( "bold" ) != -1 )
	{
		fs |= Font.BOLD;
	}
	if ( lcf.indexOf( "italic" ) != -1 || lcf.indexOf( "oblique" ) != -1 )
	{
		fs |= Font.ITALIC;
	}
	if ( ( fontStyle & Font.BOLDITALIC ) == fs )
	{
		if ( fontWeight > 400 && fontWeight != 700 )
		{
			// not a regular bold font.
			return true;
		}
		else
		{
			return false;
		}
	}
	return true;
}
 
Example #17
Source File: AsianFontMapper.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
public BaseFont awtToPdf(Font font) {
	try {
		BaseFontParameters p = getBaseFontParameters(font.getFontName());
		if (p != null){
			return BaseFont.createFont(p.fontName, p.encoding, p.embedded, p.cached, p.ttfAfm, p.pfb);
		}else{
			return BaseFont.createFont(defaultFont, encoding, true);
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	return null;

}
 
Example #18
Source File: PDFUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Font getFont( String fontPath, float size )
{
    try
    {
        BaseFont baseFont = BaseFont.createFont( fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED );
        return new Font( baseFont, size );
    }
    catch ( Exception ex )
    {
        throw new RuntimeException( "Error while creating base font", ex );
    }
}
 
Example #19
Source File: ITextPdfConverter.java    From yarg with Apache License 2.0 5 votes vote down vote up
@Override
public void addFont(File file) throws IOException {
    try {
        renderer.getFontResolver().addFont(file.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e) {
        throw new IOException(e);
    }
}
 
Example #20
Source File: HTMLWorker.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/** Creates a new instance of HTMLWorker */
public HTMLWorker(DocListener document) {
	this.document = document;
	cprops = new ChainedProperties();
	String fontName = ServerConfigurationService.getString("pdf.default.font");
	if (StringUtils.isNotBlank(fontName)) {
		FontFactory.registerDirectories();
		if (FontFactory.isRegistered(fontName)) {
			HashMap fontProps = new HashMap();
			fontProps.put(ElementTags.FACE, fontName);
			fontProps.put("encoding", BaseFont.IDENTITY_H);
			cprops.addToChain("face", fontProps);
		}
	}
}
 
Example #21
Source File: ITextBuiltInFontRegistry.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private FontFamily createHelveticaFamily() {
  final DefaultFontFamily fontFamily = new DefaultFontFamily( "Helvetica" );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.HELVETICA, false, false, false ) );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.HELVETICA_BOLD, true, false, false ) );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.HELVETICA_OBLIQUE, false, true, true ) );
  fontFamily
    .addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.HELVETICA_BOLDOBLIQUE, true, true, true ) );
  return fontFamily;
}
 
Example #22
Source File: FactoryProperties.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Font getFont(ChainedProperties props) {
	String face = props.getProperty(ElementTags.FACE);
	if (face != null) {
		StringTokenizer tok = new StringTokenizer(face, ",");
		while (tok.hasMoreTokens()) {
			face = tok.nextToken().trim();
			if (face.startsWith("\""))
				face = face.substring(1);
			if (face.endsWith("\""))
				face = face.substring(0, face.length() - 1);
			if (fontImp.isRegistered(face))
				break;
		}
	}
	int style = 0;
	if (props.hasProperty(HtmlTags.I))
		style |= Font.ITALIC;
	if (props.hasProperty(HtmlTags.B))
		style |= Font.BOLD;
	if (props.hasProperty(HtmlTags.U))
		style |= Font.UNDERLINE;
	if (props.hasProperty(HtmlTags.S))
		style |= Font.STRIKETHRU;
	String value = props.getProperty(ElementTags.SIZE);
	float size = 12;
	if (value != null)
		size = Float.parseFloat(value);
	Color color = Markup.decodeColor(props.getProperty("color"));
	String encoding = props.getProperty("encoding");
	if (encoding == null)
		encoding = BaseFont.WINANSI;
	return fontImp.getFont(face, encoding, true, size, style, color);
}
 
Example #23
Source File: BaseFontFontMetrics.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public BaseFontFontMetrics( final FontNativeContext record, final BaseFont baseFont, final float size ) {
  if ( baseFont == null ) {
    throw new NullPointerException( "BaseFont is invalid." );
  }

  this.record = record;
  this.baseFont = baseFont;
  this.size = size;
  this.cpBuffer = new char[ 4 ];
  this.cachedWidths = new long[ 256 - 32 ];
  Arrays.fill( cachedWidths, -1 );

  sizeScaled = FontStrictGeomUtility.toInternalValue( size );

  this.ascent = (long) baseFont.getFontDescriptor( BaseFont.AWT_ASCENT, sizeScaled );
  this.descent = (long) -baseFont.getFontDescriptor( BaseFont.AWT_DESCENT, sizeScaled );
  this.leading = (long) baseFont.getFontDescriptor( BaseFont.AWT_LEADING, sizeScaled );
  italicsAngle = FontStrictGeomUtility.toInternalValue( baseFont.getFontDescriptor( BaseFont.ITALICANGLE, size ) );
  maxAscent = (long) baseFont.getFontDescriptor( BaseFont.BBOXURY, sizeScaled );
  maxDescent = (long) -baseFont.getFontDescriptor( BaseFont.BBOXLLY, sizeScaled );
  maxCharAdvance = (long) baseFont.getFontDescriptor( BaseFont.AWT_MAXADVANCE, sizeScaled );

  final int[] charBBox = this.baseFont.getCharBBox( 'x' );
  if ( charBBox != null ) {
    this.xHeight = (long) ( charBBox[ 3 ] * size );
  }
  if ( this.xHeight == 0 ) {
    this.xHeight = getAscent() / 2;
  }
  this.trueTypeFont = baseFont.getFontType() == BaseFont.FONT_TYPE_TT ||
    baseFont.getFontType() == BaseFont.FONT_TYPE_TTUNI;
}
 
Example #24
Source File: FontConfigReaderTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isMappedTo( char c, String from, String to )
{
	FontHandler handler = new FontHandler( fontMappingManager,
			new String[]{from}, Font.NORMAL, true );
	BaseFont font = handler.getMappedFont( c );
	return hasName( font, to );
}
 
Example #25
Source File: TrueTypeCollectionsTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Using true type collections.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {
	
	// TODO multiplatform test
	if (!Executable.isWindows()){
		return;
	}
	// step 1: creation of a document-object
	Document document = new Document();

	BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "msgothic.txt"));
	String[] names = BaseFont.enumerateTTCNames("c:\\windows\\fonts\\msgothic.ttc");
	for (int i = 0; i < names.length; i++) {
		out.write("font " + i + ": " + names[i]);
		out.write("\r\n");
	}
	out.flush();
	out.close();
	// step 2: creation of the writer
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("truetypecollections.pdf"));

	// step 3: we open the document
	document.open();

	// step 4: we add content to the document
	BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\msgothic.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

	Font font = new Font(bf, 16);
	String text1 = "\u5951\u7d04\u8005\u4f4f\u6240\u30e9\u30a4\u30f3\uff11";
	String text2 = "\u5951\u7d04\u8005\u96fb\u8a71\u756a\u53f7";
	document.add(new Paragraph(text1, font));
	document.add(new Paragraph(text2, font));

	// step 5: we close the document
	document.close();
}
 
Example #26
Source File: TrueTypeTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Embedding True Type Fonts.
 */
@Test
public void main() throws Exception {



	// step 1: creation of a document-object
	Document document = new Document();

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "truetype.pdf"));

	// step 3: we open the document
	document.open();

	// step 4: we add content to the document
	BaseFont bfComic = BaseFont.createFont(PdfTestBase.RESOURCES_DIR + "/liberation-fonts-ttf/LiberationSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	Font font = new Font(bfComic, 12);
	String text1 = "This is the quite popular True Type font 'LiberationSans'.";
	String text2 = "Some greek characters: \u0393\u0394\u03b6";
	String text3 = "Some cyrillic characters: \u0418\u044f";
	document.add(new Paragraph(text1, font));
	document.add(new Paragraph(text2, font));
	document.add(new Paragraph(text3, font));

	// step 5: we close the document
	document.close();
}
 
Example #27
Source File: UnicodeExampleTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
    * Embedding True Type Fonts.
    * @param args no arguments needed
    */
@Test
public void main() throws Exception {


	// step 1: creation of a document-object
	Document document = new Document();

	// step 2: creation of the writer-object
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("unicode.pdf"));

	// step 3: we open the document
	document.open();
	File fontPath = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
	// step 4: we add content to the document
	BaseFont bfComic = BaseFont.createFont(fontPath.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	Font font = new Font(bfComic, 12);
	String text1 = "This is the quite popular True Type font 'Liberation Mono'.";
	String text2 = "Some greek characters: \u0393\u0394\u03b6";
	String text3 = "Some cyrillic characters: \u0418\u044f";
	document.add(new Paragraph(text1, font));
	document.add(new Paragraph(text2, font));
	document.add(new Paragraph(text3, font));

	// step 5: we close the document
	document.close();
}
 
Example #28
Source File: ShadingPatternTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Shading example.
 */
@Test
public void main() throws Exception {
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	PdfWriter writer = PdfWriter.getInstance(document,
			PdfTestBase.getOutputStream("shading_pattern.pdf"));
	document.open();

	PdfShading shading = PdfShading.simpleAxial(writer, 100, 100, 400, 100,
			Color.red, Color.cyan);
	PdfShadingPattern shadingPattern = new PdfShadingPattern(shading);
	PdfContentByte cb = writer.getDirectContent();
	BaseFont bf = BaseFont.createFont(BaseFont.TIMES_BOLD,
			BaseFont.WINANSI, false);
	cb.setShadingFill(shadingPattern);
	cb.beginText();
	cb.setTextMatrix(100, 100);
	cb.setFontAndSize(bf, 40);
	cb.showText("Look at this text!");
	cb.endText();
	PdfShading shadingR = PdfShading.simpleRadial(writer, 200, 500, 50,
			300, 500, 100, new Color(255, 247, 148), new Color(247, 138,
					107), false, false);
	cb.paintShading(shadingR);
	cb.sanityCheck();
	document.close();

}
 
Example #29
Source File: ITextBuiltInFontRegistry.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private FontFamily createTimesFamily() {
  final DefaultFontFamily fontFamily = new DefaultFontFamily( "Times" );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.TIMES_ROMAN, false, false, false ) );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.TIMES_BOLD, true, false, false ) );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.TIMES_ITALIC, false, true, false ) );
  fontFamily.addFontRecord( new ITextBuiltInFontRecord( fontFamily, BaseFont.TIMES_BOLDITALIC, true, true, false ) );
  return fontFamily;
}
 
Example #30
Source File: VerticalTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Writing vertical text.
 */
@Test
public void main() throws Exception {
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	texts[3] = convertCid(texts[0]);
	texts[4] = convertCid(texts[1]);
	texts[5] = convertCid(texts[2]);
	PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("vertical.pdf"));
	int idx = 0;
	document.open();
	PdfContentByte cb = writer.getDirectContent();
	for (int j = 0; j < 2; ++j) {
		BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j],	false);
		cb.setRGBColorStroke(255, 0, 0);
		cb.setLineWidth(0);
		float x = 400;
		float y = 700;
		float height = 400;
		float leading = 30;
		int maxLines = 6;
		for (int k = 0; k < maxLines; ++k) {
			cb.moveTo(x - k * leading, y);
			cb.lineTo(x - k * leading, y - height);
		}
		cb.rectangle(x, y, -leading * (maxLines - 1), -height);
		cb.stroke();
		VerticalText vt = new VerticalText(cb);
		vt.setVerticalLayout(x, y, height, maxLines, leading);
		vt.addText(new Chunk(texts[idx++], new Font(bf, 20)));
		vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue)));
		vt.go();
		vt.setAlignment(Element.ALIGN_RIGHT);
		vt.addText(new Chunk(texts[idx++],	new Font(bf, 20, 0, Color.orange)));
		vt.go();
		document.newPage();
	}
	document.close();

}