com.itextpdf.text.pdf.BaseFont Java Examples

The following examples show how to use com.itextpdf.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: DynamicFooter.java    From testarea-itext5 with GNU Affero General Public License v3.0 11 votes vote down vote up
public PdfPTable generateFooter() {
    try {
        BaseFont baseFont = BaseFont.createFont(/*"resources/ARIAL.TTF"*/ "c:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, true);
        footerTable = new PdfPTable(1);
        footerTable.setTotalWidth(440);
        footerTable.setLockedWidth(true);

        Font pageNumberFont = new Font(baseFont, 9, Font.BOLD);
        Paragraph pageNumberP = new Paragraph(titleIndex+"-"+ pageNumber, pageNumberFont);
        PdfPCell pageNumberCell = new PdfPCell(pageNumberP);
        pageNumberCell.setBorder(0);
        pageNumberCell.setPaddingTop(20);
        footerTable.addCell(pageNumberCell);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return footerTable;
}
 
Example #2
Source File: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 9 votes vote down vote up
/**
 * The OP's original code transformed into Java
 */
void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setColorFill(new BaseColor(255,200,200));
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example #3
Source File: StampColoredText.java    From testarea-itext5 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * The OP's code transformed into Java changed with the work-around.
 */
void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException
{
    Date today = new Date();
    PdfReader reader = new PdfReader(source);
    PdfStamper stamper = new PdfStamper(reader, target);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
    int tSize = 24;
    String mark = "DRAFT " + today;
    int angle = 45;
    float height = reader.getPageSizeWithRotation(1).getHeight()/2;
    float width = reader.getPageSizeWithRotation(1).getWidth()/2;
    PdfContentByte cb = stamper.getOverContent(1);
    cb.setFontAndSize(bf, tSize);
    cb.beginText();
    cb.setColorFill(new BaseColor(255,200,200));
    cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle);
    cb.endText();
    stamper.close();
    reader.close();
}
 
Example #4
Source File: PDFUtil.java    From roncoo-education with MIT License 7 votes vote down vote up
/**
 * 水印
 */
public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException {
	PdfReader reader = new PdfReader(src.getInputStream());
	PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest)));
	int total = reader.getNumberOfPages() + 1;
	PdfContentByte content;
	BaseFont base = BaseFont.createFont();
	for (int i = 1; i < total; i++) {
		content = stamper.getOverContent(i);// 在内容上方加水印
		content.beginText();
		content.setTextMatrix(70, 200);
		content.setFontAndSize(base, 30);
		content.setColorFill(BaseColor.GRAY);
		content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45);
		content.endText();
	}
	stamper.close();
}
 
Example #5
Source File: FontBuilder.java    From ureport with Apache License 2.0 6 votes vote down vote up
private BaseFont getIdentityFont(String fontFamily,String fontPath,ApplicationContext applicationContext) throws DocumentException,IOException {
	if(!fontPath.startsWith(ApplicationContext.CLASSPATH_URL_PREFIX)){
		fontPath=ApplicationContext.CLASSPATH_URL_PREFIX+fontPath;
	}
	String fontName = fontPath;
	int lastSlashPos=fontPath.lastIndexOf("/");
	if(lastSlashPos!=-1){
		fontName = fontPath.substring(lastSlashPos+1,fontPath.length());			
	}
	if (fontName.toLowerCase().endsWith(".ttc")) {
		fontName = fontName + ",0";
	}
	InputStream inputStream=null;
	try{
		fontPathMap.put(fontFamily, fontPath);
		inputStream=applicationContext.getResource(fontPath).getInputStream();
		byte[] bytes = IOUtils.toByteArray(inputStream);
		BaseFont baseFont = BaseFont.createFont(fontName, BaseFont.IDENTITY_H,BaseFont.EMBEDDED,true,bytes,null);
		baseFont.setSubset(true);
		return baseFont;			
	}finally{
		if(inputStream!=null)inputStream.close();
	}
}
 
Example #6
Source File: TTFontCache.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public com.itextpdf.text.Font getFont(String family, String charset, int style, float size) {
  FontKey key = new FontKey(family, charset, style, size);
  com.itextpdf.text.Font result = myFontCache.get(key);
  if (result == null) {
    Function<String, BaseFont> f = myMap_Family_ItextFont.get(family);
    BaseFont bf = f == null ? getFallbackFont(charset) : f.apply(charset);
    if (bf != null) {
      result = new com.itextpdf.text.Font(bf, size, style);
      myFontCache.put(key, result);
    } else {
      GPLogger.log(new RuntimeException("Font with family=" + family + " not found. Also tried fallback font"));
    }
  }
  return result;

}
 
Example #7
Source File: FontBuilder.java    From ureport with Apache License 2.0 6 votes vote down vote up
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	FontBuilder.applicationContext=applicationContext;
	GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
	String[] fontNames=environment.getAvailableFontFamilyNames();
	for(String name:fontNames){
		systemFontNameList.add(name);
	}
	Collection<FontRegister> fontRegisters=applicationContext.getBeansOfType(FontRegister.class).values();
	for(FontRegister fontReg:fontRegisters){
		String fontName=fontReg.getFontName();
		String fontPath=fontReg.getFontPath();
		if(StringUtils.isEmpty(fontPath) || StringUtils.isEmpty(fontName)){
			continue;
		}
		try {
			BaseFont baseFont=getIdentityFont(fontName,fontPath,applicationContext);
			if(baseFont==null){
				throw new ReportComputeException("Font " + fontPath + " does not exist");
			}
			fontMap.put(fontName, baseFont);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ReportComputeException(e);
		}
	}
}
 
Example #8
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * Helper method of the OP.
 * </p>
 * @see #testUseRowspanLikeUser7968180()
 * @see #testUseRowspanLikeUser7968180Fixed()
 * @see #createPdf(String)
 * @see #createPdfFixed(String)
 */
private static void addCellToTableCzech(PdfPTable table, int horizontalAlignment,
        int verticalAlignment, String value, int colspan, int rowspan,
        String fontType, float fontSize) {
    BaseFont base = null;
    try {
        base = BaseFont.createFont(fontType, BaseFont.CP1250, BaseFont.EMBEDDED);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Font font = new Font(base, fontSize);
    PdfPCell cell = new PdfPCell(new Phrase(value, font));
    cell.setColspan(colspan);
    cell.setRowspan(rowspan);
    cell.setHorizontalAlignment(horizontalAlignment);
    cell.setVerticalAlignment(verticalAlignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);
}
 
Example #9
Source File: DoubleSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35699167/double-space-not-being-preserved-in-pdf">
 * Double space not being preserved in PDF
 * </a>
 * <p>
 * Indeed, the double space collapses into a single one when copying&pasting from the
 * generated PDF displayed in Adobe Reader. On the other hand the gap for the double
 * space is twice as wide as for the single space. So this essentially is a quirk of
 * copy&paste of Adobe Reader (and some other PDF viewers, too).
 * </p>
 */
@Test
public void testDoubleSpace() throws DocumentException, IOException
{
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "DoubleSpace.pdf")))
    {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorderWidth(0.5f);
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("DOUBLE  SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("TRIPLE   SPACED", new Font(BaseFont.createFont(), 36)));

        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();
        pdfDocument.add(table);
        pdfDocument.close();
    }
}
 
Example #10
Source File: AppearanceAndRotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException {
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight());

    cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight());
    cs.fill();

    cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);                        
    cs.beginText();
    cs.setLeading(12 + 1.75f);
    cs.moveText(.75f, rect.getHeight() - 12 + .75f);
    cs.showText(contents);
    cs.endText();

    return PdfAnnotation.createFreeText(writer, rect, contents, cs);
}
 
Example #11
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}. This test creates a new PDF with the same
 * font and chunk as stamped by the OP. Adobe Reader has no problem with it either.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testCreateUnicodePdf() throws DocumentException, IOException
{
    Document document = new Document();
    try (   OutputStream result  = new FileOutputStream(new File(RESULT_FOLDER, "unicodePdf.pdf")) )
    {
        PdfWriter.getInstance(document, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        document.open();
        
        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        document.add(p);
        
        document.close();
    }
}
 
Example #12
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With
 * a different starting file, though, it doesn't as this test shows.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampEg_01() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("eg_01.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);

        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example #13
Source File: StampUnicodeText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext">
 * Adobe Reader can't display unicode font of pdf added with iText
 * </a>
 * <br/>
 * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0">
 * sampleOriginal.pdf
 * </a>
 * <p>
 * Indeed, just like in the iTextSharp version of the code, the resulting file has
 * issues in Adobe Reader. With a different starting file, though, it doesn't, cf.
 * {@link #testAddUnicodeStampEg_01()}.
 * </p>
 * <p>
 * As it eventually turns out, Adobe Reader treats PDF files with composite fonts
 * differently if they claim to be PDF-1.2 like the OP's sample file.
 * </p>
 */
@Test
public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf");
            OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf"))  )
    {
        PdfReader reader = new PdfReader(resource);
        PdfStamper stamper = new PdfStamper(reader, result);
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        PdfContentByte cb = stamper.getOverContent(1);

        Phrase p = new Phrase();
        p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE));
        p.add("Sample Text");

        ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0);
        
        stamper.close();
    }
}
 
Example #14
Source File: UseColumnText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment">
 * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment
 * </a>
 * <p>
 * Indeed, the coordinates do not line up. The y coordinate of 
 * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)}
 * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds
 * the text to come.
 * </p>
 */
@Test
public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException
{
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf")));
    document.open();

    Font fontQouteItems = new Font(BaseFont.createFont(), 12);
    PdfContentByte canvas = writer.getDirectContent();

    // Item Number
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0);

    // Estimated Qty
    ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0);

    // Item Description
    ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping
    ct.setSimpleColumn(new Rectangle(193, 070, 390, 450));
    ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems));
    ct.go();

    document.close();
}
 
Example #15
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createClippingTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();
    directContent.beginText();
    directContent.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_CLIP);
    directContent.setTextMatrix(AffineTransform.getTranslateInstance(100, 400));
    directContent.setFontAndSize(BaseFont.createFont(), 100);
    directContent.showText("Test");
    directContent.endText();
    
    BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 500, 0, 0, 599, 50, 50);
    document.close();

    return baos.toByteArray();
}
 
Example #16
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createSimplePatternPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();
    Rectangle pageSuze = document.getPageSize();
    
    PdfPatternPainter painter = directContent.createPattern(200, 150);
    painter.setColorStroke(BaseColor.GREEN);
    painter.beginText();
    painter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_STROKE);
    painter.setTextMatrix(AffineTransform.getTranslateInstance(0, 50));
    painter.setFontAndSize(BaseFont.createFont(), 100);
    painter.showText("Test");
    painter.endText();

    directContent.setColorFill(new PatternColor(painter));
    directContent.rectangle(pageSuze.getLeft(), pageSuze.getBottom(), pageSuze.getWidth(), pageSuze.getHeight());
    directContent.fill();

    document.close();

    return baos.toByteArray();
}
 
Example #17
Source File: Resource.java    From excel2pdf with Apache License 2.0 5 votes vote down vote up
/**
 * 將 POI Font 轉換到 iText Font
 * @param font
 * @return
 */
public static com.itextpdf.text.Font getFont(HSSFFont font) {
    try {
        com.itextpdf.text.Font iTextFont = FontFactory.getFont(font.getFontName(),
                BaseFont.IDENTITY_H, BaseFont.EMBEDDED,
                font.getFontHeightInPoints());
        return iTextFont;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #18
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private Font getFont(String color, boolean bold) throws Exception {
	Font font = FontFactory.getFont(BscConstants.PDF_ITEXT_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	int rgb[] = SimpleUtils.getColorRGB2(color);
	BaseColor baseColor = new BaseColor(rgb[0], rgb[1], rgb[2]);
	font.setSize(9);
	font.setColor(baseColor);
	return font;
}
 
Example #19
Source File: TrpPdfDocument.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
private boolean writeDocMd(String mdName, String mdValue, float posYdirection, int horizontalPlacement,
		float lineHeight, PdfContentByte cb, BaseFont bfArialItalic) {
	if (mdValue != null && !mdValue.equals("")){
		
		if (posYdirection > (twelfthPoints[11][1])){
			posYdirection = twelfthPoints[1][1];
		}
		addTitleString(mdName + mdValue, posYdirection, horizontalPlacement, lineHeight, cb, bfArialItalic);
		return true;
	}
	return false;
	
}
 
Example #20
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private Font getFont(String color, boolean bold) throws Exception {
	Font font = FontFactory.getFont(BscConstants.PDF_ITEXT_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	int rgb[] = SimpleUtils.getColorRGB2(color);
	BaseColor baseColor = new BaseColor(rgb[0], rgb[1], rgb[2]);
	font.setSize(9);
	font.setColor(baseColor);
	return font;
}
 
Example #21
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
private Font getFont(String color, boolean bold) throws Exception {
	Font font = FontFactory.getFont(BscConstants.PDF_ITEXT_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	int rgb[] = SimpleUtils.getColorRGB2(color);
	BaseColor baseColor = new BaseColor(rgb[0], rgb[1], rgb[2]);
	font.setSize(9);
	if (bold) {
		font.setSize(14);
		font.setStyle(Font.BOLD);
	}		
	font.setColor(baseColor);
	return font;
}
 
Example #22
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 4 votes vote down vote up
protected AbstractPdfReportBuilder() throws Exception {
	chineseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
}
 
Example #23
Source File: TTFontCache.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
static void clearCache() {
  BaseFont.fontCache.clear();
}
 
Example #24
Source File: PDFPainter.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void init(PdfContentByte gc){
	this.cb = gc;
	this.background = new PDFColor(0xff, 0xff, 0xff);
	this.foreground = new PDFColor(0x00, 0x00, 0x00);
	this.font = new PDFFont(BaseFont.HELVETICA, 9, false, false);
}
 
Example #25
Source File: PDFLayoutStyles.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
public PDFLayoutStyles() {
	this.setBufferEnabled(false);
	this.setFirstMeasureSpacing(15);
	this.setMinBufferSeparator(15);
	this.setMinTopSpacing(20);
	this.setMinScoreTabSpacing(15);
	this.setScoreLineSpacing(7);
	this.setFirstTrackSpacing(5);
	this.setTrackSpacing(5);
	this.setStringSpacing(8);
	this.setChordFretIndexSpacing(8);
	this.setChordStringSpacing(4);
	this.setChordFretSpacing(5);
	this.setChordNoteSize(3);
	this.setChordLineWidth(0);
	this.setRepeatEndingSpacing(20);
	this.setTextSpacing(15);
	this.setMarkerSpacing(15);
	this.setDivisionTypeSpacing(10);
	this.setEffectSpacing(8);
	this.setFirstNoteSpacing(10f);
	this.setMeasureLeftSpacing(15f);
	this.setMeasureRightSpacing(15f);
	this.setClefSpacing(30f);
	this.setKeySignatureSpacing(15f);
	this.setTimeSignatureSpacing(15f);
	
	this.setLineWidths(new float[] {0, 1, 2, 3, 4, 5});
	this.setDurationWidths(new float[] {18f, 18f, 16f, 15f, 14f});
	this.setDefaultFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setNoteFont(new UIFontModel(BaseFont.TIMES_BOLD, 9, true, false));
	this.setLyricFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setTextFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setGraceFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setChordFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setChordFretFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setMarkerFont(new UIFontModel(BaseFont.TIMES_ROMAN, 8, false, false));
	this.setForegroundColor(new UIColorModel(0x00,0x00,0x00));
	this.setBackgroundColor(new UIColorModel(0xff,0xff,0xff));
	this.setLineColor(new UIColorModel(0x00,0x00,0x00));
	this.setScoreNoteColor(new UIColorModel(0x00,0x00,0x00));
	this.setTabNoteColor(new UIColorModel(0x00,0x00,0x00));
	this.setPlayNoteColor(new UIColorModel(0x00,0x00,0x00));
	this.setLoopSMarkerColor(new UIColorModel(0x00,0x00,0x00));
	this.setLoopEMarkerColor(new UIColorModel(0x00,0x00,0x00));
	this.setMeasureNumberColor(new UIColorModel(0xff,0x00,0x00));
}
 
Example #26
Source File: TrpPdfDocument.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
private void highlightUniformString(Set<Entry<CustomTag, String>> entrySet, float tmpLineStartX, float lineStartY, TrpTextLineType l, PdfContentByte cb, int cutoffLeft, int cutoffTop, BaseFont bf) throws IOException {
	
	int k = 1;
	int tagId = 0;
	int [] prevLength = new int[entrySet.size()];
	int [] prevOffset = new int[entrySet.size()];
	
	for (Map.Entry<CustomTag, String> currEntry : entrySet){
		
		Set<String> wantedTags = ExportUtils.getOnlyWantedTagnames(CustomTagFactory.getRegisteredTagNames());
		
		if (wantedTags.contains(currEntry.getKey().getTagName())){

			
			//logger.debug("current tag text "+ currEntry.getKey().getContainedText());
			String color = CustomTagFactory.getTagColor(currEntry.getKey().getTagName());
			
			int currLength = currEntry.getKey().getLength();
			int currOffset = currEntry.getKey().getOffset();
			
			/**
			 * if the current tag overlaps one of the previous tags
			 * -> increase the distance of the line under the textline
			 */
			if (isOverlaped(prevOffset, prevLength, currOffset, currLength)){
				k++;
			}
			else{
				k=1;
			}
			
			prevOffset[tagId] = currOffset;
			prevLength[tagId] = currLength;
			tagId++;
			
			//yShift -> vertical shift of underline if several tags are at the same position
			float yShift = (lineMeanHeight/6) * k;
			highlightUniformTagString(lineMeanHeight, tmpLineStartX, lineStartY, l.getUnicodeText(), currEntry.getKey().getContainedText(), cb, cutoffLeft, cutoffTop, bf, twelfthPoints[1][0], color, yShift, currOffset);
		}
	}
	
}
 
Example #27
Source File: TrpPdfDocument.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
public TrpPdfDocument(final File pdfFile, final int marginLeft, final int marginTop, final int marginBottom, final int marginRight, final boolean useWordLevel, final boolean highlightTags, final boolean highlightArticles, final boolean doBlackening, boolean createTitle, final String exportFontname, ImgType pdfImgType) throws DocumentException, IOException {
		super(pdfFile, marginLeft, marginTop, marginBottom, marginRight);
		this.useWordLevel = useWordLevel;
		this.highlightTags = highlightTags;
		this.highlightArticles = highlightArticles;
		this.doBlackening = doBlackening;
		this.createTitle = createTitle;
		
		if (pdfImgType != null){
			this.imgType = pdfImgType;
		}
		
		//logger.debug(" path to fonts : " + this.getClass().getClassLoader().getResource("fonts").getPath());
		FontFactory.registerDirectory(this.getClass().getClassLoader().getResource("fonts").getPath());
	    Set<String> fonts = new TreeSet<String>(FontFactory.getRegisteredFonts());
//	    for (String fontname : fonts) {
//	        logger.debug("registered font name : " + fontname);
//	    }
	    
	    if (exportFontname != null){
		    logger.debug("chosen font name: " + exportFontname);
		    mainExportFont = FontFactory.getFont(exportFontname, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		    boldFont = FontFactory.getFont(exportFontname + " bold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		    italicFont = FontFactory.getFont(exportFontname + " italic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		    boldItalicFont = FontFactory.getFont(exportFontname + " bold italic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	    }
	    
	    mainExportFont = (mainExportFont != null && mainExportFont.getFamilyname() != "unknown")? mainExportFont : new Font(bfSerif);
	    mainExportBaseFont = (mainExportFont.getBaseFont() != null)? mainExportFont.getBaseFont() : bfSerif;
	    
	    boldFont = (boldFont != null && boldFont.getFamilyname() != "unknown")? boldFont : new Font(bfSerifBold);
	    boldBaseFont = (boldFont.getBaseFont() != null)? boldFont.getBaseFont() : bfSerifBold;
	    
	    italicFont = (italicFont != null && italicFont.getFamilyname() != "unknown")? italicFont : new Font(bfSerifItalic);
	    italicBaseFont = (italicFont.getBaseFont() != null)? italicFont.getBaseFont() : bfSerifItalic;
		
	    boldItalicFont = (boldItalicFont != null && boldItalicFont.getFamilyname() != "unknown")? boldItalicFont : new Font(bfSerifBoldItalic);
	    boldItalicBaseFont = (boldItalicFont.getBaseFont() != null)? boldItalicFont.getBaseFont() : bfSerifBoldItalic;

		logger.debug("main font family found: " + mainExportFont.getFamilyname());
    	logger.info("main base font for PDF export is: " + mainExportBaseFont.getPostscriptFontName());
	}
 
Example #28
Source File: PdfReportPageNumber.java    From bdf3 with Apache License 2.0 4 votes vote down vote up
public PdfReportPageNumber(BaseFont font){
	this.chineseFont=font;
}
 
Example #29
Source File: POIUtil.java    From excel2pdf with Apache License 2.0 4 votes vote down vote up
public static com.itextpdf.text.Font toItextFont(org.apache.poi.ss.usermodel.Font font) {
    com.itextpdf.text.Font iTextFont = FontFactory.getFont(font.getFontName(),
            BaseFont.IDENTITY_H, BaseFont.EMBEDDED,
            font.getFontHeightInPoints());
    return iTextFont;
}
 
Example #30
Source File: CreateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/34734669/define-background-color-and-transparency-of-link-annotation-in-pdf">
 * Define background color and transparency of link annotation in PDF
 * </a>
 * <p>
 * This test creates a link annotation with custom appearance. Adobe Reader chooses
 * to ignore it but other viewers use it. Interestingly Adobe Acrobat export-as-image
 * does use the custom appearance...
 * </p>
 */
@Test
public void testCreateLinkWithAppearance() throws IOException, DocumentException
{
    Document doc = new Document();
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "custom-link.appearance.pdf")));
    writer.setCompressionLevel(0);
    doc.open();

    BaseFont baseFont = BaseFont.createFont();
    int fontSize = 15;
    doc.add(new Paragraph("Hello", new Font(baseFont, fontSize)));
    
    PdfContentByte content = writer.getDirectContent();
    
    String text = "Test";
    content.setFontAndSize(baseFont, fontSize);
    content.beginText();
    content.moveText(100, 500);
    content.showText(text);
    content.endText();
    
    Rectangle linkLocation = new Rectangle(95, 495 + baseFont.getDescentPoint(text, fontSize),
            105 + baseFont.getWidthPoint(text, fontSize), 505 + baseFont.getAscentPoint(text, fontSize));

    PdfAnnotation linkGreen = PdfAnnotation.createLink(writer, linkLocation, PdfName.HIGHLIGHT, "green" );
    PdfTemplate appearance = PdfTemplate.createTemplate(writer, linkLocation.getWidth(), linkLocation.getHeight());
    PdfGState state = new PdfGState();
    //state.FillOpacity = .3f;
    // IMPROVEMENT: Use blend mode Darken instead of transparency; you may also want to try Multiply.
    state.setBlendMode(new PdfName("Darken"));
    appearance.setGState(state);

    appearance.setColorFill(BaseColor.GREEN);
    appearance.rectangle(0, 0, linkLocation.getWidth(), linkLocation.getHeight());
    appearance.fill();
    linkGreen.setAppearance(PdfName.N, appearance);
    writer.addAnnotation(linkGreen);

    doc.open();
    doc.close();
}