Java Code Examples for org.apache.pdfbox.pdmodel.font.PDType1Font

The following are top voted examples for showing how to use org.apache.pdfbox.pdmodel.font.PDType1Font. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License 11 votes vote down vote up
@Test
public void createRingManagerDocument() throws Exception {
    final PDDocument document = new PDDocument();
    final PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);

    final float startY = page.getMediaBox().getHeight() - 150;
    final int startX = 56;

    final PDPageContentStream contentStream = new PDPageContentStream(document, page);
    Table table = getRingManagerTable();

    (new TableDrawer(contentStream, table, startX, startY)).draw();

    contentStream.setFont(PDType1Font.HELVETICA, 8.0f);
    contentStream.beginText();

    contentStream.newLineAtOffset(startX, startY - (table.getHeight() + 22));
    contentStream.showText("Dieser Kampf muss der WB nicht entsprechen, da als Sparringskampf angesetzt.");
    contentStream.endText();

    contentStream.close();

    document.save("target/ringmanager.pdf");
    document.close();
}
 
Example 2
Project: esup-ecandidat   File: CandidatureController.java   Source Code and License 10 votes vote down vote up
/**
 * @param textHeader
 * @param font
 * @param PAGE_SIZE_A4
 * @param contentStream
 * @return ajoute un header a la piece
 * @throws IOException
 */
private Float addHeaderPJ(final String textHeader, final PDFont font, final PDRectangle PAGE_SIZE_A4,
		final PDPageContentStream contentStream) throws IOException {
	Float marginTop = 0f;
	// si font Ok, on ajoute le text
	if (font != null && ConstanteUtils.DOSSIER_ADD_HEADER_IMG) {

		// calcul de la largeur et hauteur du txt
		Float titleWidth = font.getStringWidth(textHeader) / 1000 * ConstanteUtils.DOSSIER_FONT_SIZE;
		Float titleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000
				* ConstanteUtils.DOSSIER_FONT_SIZE;

		// calcul de la marge du haut : hauteur du text + marge
		marginTop = titleHeight + ConstanteUtils.DOSSIER_MARGIN;

		// calcul de la position du text
		Float xText = (PAGE_SIZE_A4.getWidth() - 2 * ConstanteUtils.DOSSIER_MARGIN - titleWidth) / 2;
		Float yText = PAGE_SIZE_A4.getHeight() - marginTop;

		// ecriture du text
		contentStream.beginText();
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, ConstanteUtils.DOSSIER_FONT_SIZE);
		contentStream.newLineAtOffset(xText, yText);
		contentStream.showText(textHeader);
		contentStream.endText();
	}
	return marginTop;
}
 
Example 3
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License 8 votes vote down vote up
@Test
public void createSampleDocument() throws Exception {
    // Define the table structure first
    TableBuilder tableBuilder = new TableBuilder()
            .addColumnOfWidth(300)
            .addColumnOfWidth(120)
            .addColumnOfWidth(70)
            .setFontSize(8)
            .setFont(PDType1Font.HELVETICA);

    // Header ...
    tableBuilder.addRow(new RowBuilder()
            .add(Cell.withText("This is right aligned without a border").setHorizontalAlignment(RIGHT))
            .add(Cell.withText("And this is another cell"))
            .add(Cell.withText("Sum").setBackgroundColor(Color.ORANGE))
            .setBackgroundColor(Color.BLUE)
            .build());

    // ... and some cells
    for (int i = 0; i < 10; i++) {
        tableBuilder.addRow(new RowBuilder()
                .add(Cell.withText(i).withAllBorders())
                .add(Cell.withText(i * i).withAllBorders())
                .add(Cell.withText(i + (i * i)).withAllBorders())
                .setBackgroundColor(i % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE)
                .build());
    }

    final PDDocument document = new PDDocument();
    final PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);

    final PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define the starting point
    final float startY = page.getMediaBox().getHeight() - 50;
    final int startX = 50;

    // Draw!
    (new TableDrawer(contentStream, tableBuilder.build(), startX, startY)).draw();
    contentStream.close();

    document.save("target/sampleWithColorsAndBorders.pdf");
    document.close();
}
 
Example 4
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License 8 votes vote down vote up
private void generateBillHeader(PDPage firstPage, PDPageContentStream contentStream)
        throws IOException {
    // Add header text
    PDFont currentFont;
    int currentFontSize;
    String headerLine1 = "Git Rekt Resort";
    String headerLine2 = "Customer Bill";
    contentStream.setLeading(10);
    currentFont = BOLD;
    currentFontSize = 14;
    contentStream.setFont(currentFont, currentFontSize);
    contentStream.beginText();
    float offsetX = getCenteredTextXPos(firstPage, headerLine1, currentFont, currentFontSize);
    contentStream.newLineAtOffset(offsetX, 750f);
    contentStream.showText(headerLine1);
    currentFont = PDType1Font.COURIER_BOLD;
    currentFontSize = 12;
    contentStream.setFont(currentFont, currentFontSize);
    float offsetX2 = getCenteredTextXPos(firstPage, headerLine2, currentFont, currentFontSize);
    contentStream.newLineAtOffset(-offsetX + offsetX2, -5f);
    contentStream.newLine();
    contentStream.showText(headerLine2);
    contentStream.endText();
}
 
Example 5
Project: melon   File: PdfDemo.java   Source Code and License 8 votes vote down vote up
@Test
public void test001() throws IOException {
    //E:\Repository\Git\melon\melon-sample-pdf\src\main\resources\HTTP权威指南.pdf
    System.out.println("Hello World!");

    PDDocument pdDocument = new PDDocument();
    PDPage pdPage = new PDPage();
    pdDocument.addPage(pdPage);

    PDFont pdFont = PDType1Font.HELVETICA_BOLD;

    PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdPage);
    contentStream.beginText();
    contentStream.setFont(pdFont, 14);
    contentStream.newLineAtOffset(100, 700);
    contentStream.showText("Hello World");
    contentStream.endText();
    contentStream.close();

    String directory = PdfDemo.class.getClassLoader().getResource("").getPath();
    String fileName = "text.pdf";

    pdDocument.save(directory + fileName);
    pdDocument.close();
}
 
Example 6
Project: testarea-pdfbox1   File: InsertPages.java   Source Code and License 8 votes vote down vote up
public PDDocument create100Pages() throws IOException
{
    PDDocument document = new PDDocument();
    
    for (int i = 0; i < 100; i++)
    {
        PDPage page = new PDPage();
        document.addPage(page);
        PDPageContentStream content = new PDPageContentStream(document, page);
        content.beginText();
        content.setFont(PDType1Font.HELVETICA_BOLD, 100);
        content.moveTextPositionByAmount(100, 300);
        content.drawString(String.format("-%s-", i + 1));
        content.endText();
        content.close();
    }
    
    return document;
}
 
Example 7
Project: FYS_T3   File: statisticsController.java   Source Code and License 7 votes vote down vote up
@FXML
public void printPDFFile(ActionEvent event) throws IOException {
    try {
        String fileName = "PDFoutput.pdf";

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);

        content.beginText();
        content.setFont(PDType1Font.TIMES_ROMAN, 26);
        content.moveTextPositionByAmount(220, 750);
        content.drawString("Titel");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.TIMES_ROMAN, 16);
        content.moveTextPositionByAmount(80, 700);
        content.drawString("Inhoud");
        content.endText();

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("your file was saved in: " + System.getProperty("user.dir"));

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}
 
Example 8
Project: 484_P7_1-Java   File: TestProjectionProfile.java   Source Code and License 7 votes vote down vote up
@Before
public void setUpProjectionProfile() {
	PDPage pdPage = new PDPage();
	
	TextElement textElement = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "test", 1f);
	TextElement textElement2 = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "test", 1f);
	List<TextElement> textList = new ArrayList<>();
	textList.add(textElement);
	textList.add(textElement2);

	Ruling ruling = new Ruling(0, 0, 10, 10);
	List<Ruling> rulingList = new ArrayList<>();
	rulingList.add(ruling);


	page = new Page(0, 0, 1, 1, 0, 1, pdPage, textList, rulingList);
	
	List<Rectangle> rectangles = new ArrayList<>();
	rectangles.add(new Rectangle(0f, 0f, 500f, 5f));
	
	pProfile = new ProjectionProfile(page, rectangles, 5, 5);
}
 
Example 9
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 7 votes vote down vote up
@Test
public void createTextElement() {
	
	TextElement textElement = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f);
	
	Assert.assertNotNull(textElement);
	Assert.assertEquals("A", textElement.getText());
	Assert.assertEquals(1f, textElement.getFontSize(), 0);
	Assert.assertEquals(15f, textElement.getLeft(), 0);
	Assert.assertEquals(5f, textElement.getTop(), 0);
	Assert.assertEquals(10f, textElement.getWidth(), 0);
	Assert.assertEquals(20f, textElement.getHeight(), 0);
	Assert.assertEquals(PDType1Font.HELVETICA, textElement.getFont());
	Assert.assertEquals(1f, textElement.getWidthOfSpace(), 0);
	Assert.assertEquals(0f, textElement.getDirection(), 0);
	
	
}
 
Example 10
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 7 votes vote down vote up
@Test
public void createTextElementWithDirection() {
	
	TextElement textElement = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f);
	
	Assert.assertNotNull(textElement);
	Assert.assertEquals("A", textElement.getText());
	Assert.assertEquals(1f, textElement.getFontSize(), 0);
	Assert.assertEquals(15f, textElement.getLeft(), 0);
	Assert.assertEquals(5f, textElement.getTop(), 0);
	Assert.assertEquals(10f, textElement.getWidth(), 0);
	Assert.assertEquals(20f, textElement.getHeight(), 0);
	Assert.assertEquals(PDType1Font.HELVETICA, textElement.getFont());
	Assert.assertEquals(1f, textElement.getWidthOfSpace(), 0);
	Assert.assertEquals(6f, textElement.getDirection(), 0);
	
	
}
 
Example 11
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 7 votes vote down vote up
@Test
public void mergeFourElementsIntoOneWord() {
	
	List<TextElement> elements = new ArrayList<>();
	elements.add(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(0f, 25f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f));
	elements.add(new TextElement(0f, 35f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f));
	elements.add(new TextElement(0f, 45f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	
	List<TextChunk> words = TextElement.mergeWords(elements);
	
	List<TextChunk> expectedWords = new ArrayList<>();
	TextChunk textChunk = new TextChunk(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	textChunk.add(new TextElement(0f, 25f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f));
	textChunk.add(new TextElement(0f, 35f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f));
	textChunk.add(new TextElement(0f, 45f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	expectedWords.add(textChunk);
	
	Assert.assertEquals(expectedWords, words);
	
}
 
Example 12
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 7 votes vote down vote up
@Test
public void mergeElementsWithSkippingRules() {
	
	List<TextElement> elements = new ArrayList<>();
	elements.add(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(0f, 17f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(0f, 25f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f));
	elements.add(new TextElement(0.001f, 25f, 10f, 20f, PDType1Font.HELVETICA, 1f, " ", 1f, 6f));
	elements.add(new TextElement(0f, 35f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f));
	elements.add(new TextElement(0f, 45f, 10f, 20f, PDType1Font.TIMES_ROMAN, 10f, "D", 1f, 6f));
	
	List<TextChunk> words = TextElement.mergeWords(elements);
	
	List<TextChunk> expectedWords = new ArrayList<>();
	TextChunk textChunk = new TextChunk(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	textChunk.add(new TextElement(0f, 25f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f));
	textChunk.add(new TextElement(0f, 35f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f));
	textChunk.add(new TextElement(0f, 45f, 10f, 20f, PDType1Font.TIMES_ROMAN, 10f, "D", 1f, 6f));
	expectedWords.add(textChunk);
	
	Assert.assertEquals(expectedWords, words);
	
}
 
Example 13
Project: oma-riista-web   File: HunterPaymentPdfFeature.java   Source Code and License 7 votes vote down vote up
public byte[] build() throws IOException {
    this.acroForm.setNeedAppearances(false);

    // Fix annotations
    for (PDPage page : this.pdfDocument.getPages()) {
        for (PDAnnotation annot : page.getAnnotations()) {
            annot.setPage(page);
        }
    }

    // Define font resources names used in PDF template
    final PDResources dr = new PDResources();
    dr.put(COSName.getPDFName("Helv"), PDType1Font.HELVETICA);
    dr.put(COSName.getPDFName("HeBo"), PDType1Font.HELVETICA_BOLD);
    this.acroForm.setDefaultResources(dr);

    // Convert form fields to text
    this.acroForm.flatten();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    pdfDocument.save(bos);
    pdfDocument.close();
    return bos.toByteArray();
}
 
Example 14
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 7 votes vote down vote up
private void drawSectionHeader(String title, float cardXCoordinate, float cardYCoordinate, PDPage page, PDPageContentStream contentStream) throws IOException {
    // Set background color
    Color color = new Color(73, 89, 105);
    float colorBoxWidth = page.getMediaBox().getWidth() - 2 * PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    float colorBoxHeight = PdfBoxStyle.DEFAULT_TABLE_ROW_HEIGHT;
    PDFont titleFont = PDType1Font.TIMES_BOLD;
    float titleFontSize = PdfBoxStyle.TEXT_MEDIUM_SIZE;
    Color titleColor = Color.WHITE;

    pdfBoxService.addColorBox(color, cardXCoordinate, cardYCoordinate, colorBoxWidth, colorBoxHeight, page, contentStream);

    float titleYCoordinate = cardYCoordinate + (colorBoxHeight / 2)
            - ((titleFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * titleFontSize) / 4);

    pdfBoxService.addTextAtOffset(title, titleFont, titleFontSize, titleColor, cardXCoordinate + 4f, titleYCoordinate, contentStream);
}
 
Example 15
Project: testarea-pdfbox1   File: CreateCheckbox.java   Source Code and License 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/43604973/creating-a-checkbox-and-printing-it-to-pdf-file-is-not-working-using-pdfbox-1-8">
 * Creating a checkbox and printing it to pdf file is not working using pdfbox 1.8.9 api
 * </a>
 * <p>
 * The OP's method for checkbox creation.
 * </p>
 * @see #testCheckboxLikeSureshGoud()
 */
public static void writeInputFieldToPDFPage( PDPage pdPage, PDDocument document, Float x, Float y, Boolean ticked) throws IOException {
    PDFont font = PDType1Font.HELVETICA;
    PDResources res = new PDResources();
    String fontName = res.addFont(font);
    String da = ticked?"/" + fontName + " 10 Tf 0 0.4 0 rg":"";

    COSDictionary acroFormDict = new COSDictionary();
    acroFormDict.setBoolean(COSName.getPDFName("NeedAppearances"), true);
    acroFormDict.setItem(COSName.FIELDS, new COSArray());
    acroFormDict.setItem(COSName.DA, new COSString(da));

    PDAcroForm acroForm =  new PDAcroForm(document, acroFormDict);
    acroForm.setDefaultResources(res);
    document.getDocumentCatalog().setAcroForm(acroForm);

    PDGamma colourBlack = new PDGamma();
    PDAppearanceCharacteristicsDictionary fieldAppearance =
        new PDAppearanceCharacteristicsDictionary(new COSDictionary());
    fieldAppearance.setBorderColour(colourBlack);
    if(ticked) {
        COSArray arr = new COSArray();
        arr.add(new COSFloat(0.89f));
        arr.add(new COSFloat(0.937f));
        arr.add(new COSFloat(1f));
        fieldAppearance.setBackground(new PDGamma(arr));
    }

    COSDictionary cosDict = new COSDictionary();
    COSArray rect = new COSArray();

    rect.add(new COSFloat(x));
    rect.add(new COSFloat(new Float(y-5)));
    rect.add(new COSFloat(new Float(x+10)));
    rect.add(new COSFloat(new Float(y+5)));

    cosDict.setItem(COSName.RECT, rect);
    cosDict.setItem(COSName.FT, COSName.getPDFName("Btn")); // Field Type
    cosDict.setItem(COSName.TYPE, COSName.ANNOT);
    cosDict.setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
    if(ticked) {
        cosDict.setItem(COSName.TU, new COSString("Checkbox with PDFBox"));
    }
    cosDict.setItem(COSName.T, new COSString("Chk"));
    //Tick mark color and size of the mark
    cosDict.setItem(COSName.DA, new COSString(ticked?"/F0 10 Tf 0 0.4 0 rg":"/FF 1 Tf 0 0 g"));
    cosDict.setInt(COSName.F, 4);

    PDCheckbox checkbox = new PDCheckbox(acroForm, cosDict);
    checkbox.setFieldFlags(PDCheckbox.FLAG_READ_ONLY);
    checkbox.setValue("Yes");

    checkbox.getWidget().setAppearanceCharacteristics(fieldAppearance);

    pdPage.getAnnotations().add(checkbox.getWidget());
    acroForm.getFields().add(checkbox);
}
 
Example 16
Project: testarea-pdfbox1   File: RolloverAnnotation.java   Source Code and License 7 votes vote down vote up
void createRollover(PDAnnotation annotation, String filename) throws IOException, COSVisitorException
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    List<PDAnnotation> annotations = page.getAnnotations();

    float x = 100;
    float y = 500;
    String text = "PDFBox";
    PDFont font = PDType1Font.HELVETICA_BOLD;
    float textWidth = font.getStringWidth(text) / 1000 * 18;

    PDPageContentStream contents = new PDPageContentStream(document, page);
    contents.beginText();
    contents.setFont(font, 18);
    contents.moveTextPositionByAmount(x, y);
    contents.drawString(text);
    contents.endText();
    contents.close();

    PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
    PDAppearanceStream normal = createAppearanceStream(document, textWidth, font, "0.5 0.5 0.5 rg");
    PDAppearanceStream rollover = createAppearanceStream(document, textWidth, font, "1 0.7 0.5 rg");
    PDAppearanceStream down = createAppearanceStream(document, textWidth, font, "0 0 0 rg");
    appearanceDictionary.setNormalAppearance(normal);
    appearanceDictionary.setRolloverAppearance(rollover);
    appearanceDictionary.setDownAppearance(down);
    annotation.setAppearance(appearanceDictionary);

    PDRectangle position = new PDRectangle();
    position.setLowerLeftX(x);
    position.setLowerLeftY(y - 5);
    position.setUpperRightX(x + textWidth);
    position.setUpperRightY(y + 20);
    annotation.setRectangle(position);

    annotations.add(annotation);
    document.save(new File(RESULT_FOLDER, filename));
    document.close();
}
 
Example 17
Project: testarea-pdfbox1   File: ExtractWithoutExtraSpaces.java   Source Code and License 7 votes vote down vote up
byte[] createTestDocument() throws IOException, COSVisitorException
{
    try (   ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PDDocument doc = new PDDocument()   )
    {
        PDPage page = new PDPage(new PDRectangle(792, 612));
        doc.addPage(page);
        
        PDFont font = PDType1Font.COURIER;

        PDPageContentStream contents = new PDPageContentStream(doc, page);
        contents.beginText();
        contents.setFont(font, 9);
        contents.moveTextPositionByAmount(100, 500);
        contents.drawString("             2                                                                  Netto        5,00 EUR 3,00");
        contents.moveTextPositionByAmount(0, 0);
        contents.drawString("                2882892  ENERGIZE LR6 Industrial                     2,50 EUR 1");
        contents.endText();
        contents.close();
        
        doc.save(baos);
        
        return baos.toByteArray();
    }
}
 
Example 18
Project: pdfwriter   File: PageHeader.java   Source Code and License 7 votes vote down vote up
public void create(PDDocument document, PDFPage page) throws IOException {

	PDPageContentStream cs = new PDPageContentStream(document, page, true, false);
       
	PDRectangle pageSize = page.getBleedBox();
       float pageWidth = pageSize.getWidth();
       page.translateAndRotateIfNecessary(cs, pageWidth, 0);
       
	cs.beginText();
	PDFont font = PDType1Font.HELVETICA_BOLD;
	cs.setFont(font, 20);
	cs.moveTextPositionByAmount(page.getLeftX(), page.getTopY());
	cs.drawString(title);
	cs.endText();
	cs.drawLine(page.getLeftX(), page.getTopY()-height, page.getRightX(), page.getTopY()-height);
		cs.close();
}
 
Example 19
Project: pdfwriter   File: PDFTable.java   Source Code and License 7 votes vote down vote up
public void addTitleRow(String[] titles) throws IOException {
	if (hideTable)
		return;
	int size = 16;
	float cellSize = (getWidth()/titles.length);
	PDFont font = PDType1Font.HELVETICA_BOLD;
	PDPageContentStream cs = new PDPageContentStream(document, page, true, 	false);
	cs.setFont(font, size);
	float leftX = getLeftX()+30;

	for (String title : titles) {
		cs.beginText();
		cs.moveTextPositionByAmount(leftX, page.getYCursor());
		cs.drawString(title);
		cs.endText();
		if (cellSize != -1)
			leftX += cellSize;
		else
			leftX += (font.getStringWidth(title) / 1000 * size)+5;
	}
	cs.drawLine(getLeftX(), page.getYCursor() - 5, getRightX(), page.getYCursor() - 5);
	cs.close();
	
	scrolldown();
}
 
Example 20
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   Source Code and License 6 votes vote down vote up
/**
 * Find a PDFont for the given font object, which does not need to be embedded.
 * 
 * @param font
 *            font for which to find a suitable default font
 * @return null if no default font is found or a default font which does not
 *         need to be embedded.
 */
public static PDFont mapDefaultFonts(Font font) {
	/*
	 * Map default font names to the matching families.
	 */
	if (fontNameEqualsAnyOf(font, Font.SANS_SERIF, Font.DIALOG, Font.DIALOG_INPUT, "Arial", "Helvetica"))
		return chooseMatchingHelvetica(font);
	if (fontNameEqualsAnyOf(font, Font.MONOSPACED, "courier", "courier new"))
		return chooseMatchingCourier(font);
	if (fontNameEqualsAnyOf(font, Font.SERIF, "Times", "Times New Roman", "Times Roman"))
		return chooseMatchingTimes(font);
	if (fontNameEqualsAnyOf(font, "Symbol"))
		return PDType1Font.SYMBOL;
	if (fontNameEqualsAnyOf(font, "ZapfDingbats", "Dingbats"))
		return PDType1Font.ZAPF_DINGBATS;
	return null;
}
 
Example 21
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   Source Code and License 6 votes vote down vote up
/**
 * Get a PDType1Font.TIMES-variant, which matches the given font
 * 
 * @param font
 *            Font to get the styles from
 * @return a PDFont Times variant which matches the style in the given Font
 *         object.
 */
public static PDFont chooseMatchingTimes(Font font) {
	if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
		return PDType1Font.TIMES_BOLD_ITALIC;
	if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
		return PDType1Font.TIMES_ITALIC;
	if ((font.getStyle() & Font.BOLD) == Font.BOLD)
		return PDType1Font.TIMES_BOLD;
	return PDType1Font.TIMES_ROMAN;
}
 
Example 22
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   Source Code and License 6 votes vote down vote up
/**
 * Get a PDType1Font.COURIER-variant, which matches the given font
 * 
 * @param font
 *            Font to get the styles from
 * @return a PDFont Courier variant which matches the style in the given Font
 *         object.
 */
public static PDFont chooseMatchingCourier(Font font) {
	if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
		return PDType1Font.COURIER_BOLD_OBLIQUE;
	if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
		return PDType1Font.COURIER_OBLIQUE;
	if ((font.getStyle() & Font.BOLD) == Font.BOLD)
		return PDType1Font.COURIER_BOLD;
	return PDType1Font.COURIER;
}
 
Example 23
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFonts.java   Source Code and License 6 votes vote down vote up
/**
 * Get a PDType1Font.HELVETICA-variant, which matches the given font
 * 
 * @param font
 *            Font to get the styles from
 * @return a PDFont Helvetica variant which matches the style in the given Font
 *         object.
 */
public static PDFont chooseMatchingHelvetica(Font font) {
	if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD))
		return PDType1Font.HELVETICA_BOLD_OBLIQUE;
	if ((font.getStyle() & Font.ITALIC) == Font.ITALIC)
		return PDType1Font.HELVETICA_OBLIQUE;
	if ((font.getStyle() & Font.BOLD) == Font.BOLD)
		return PDType1Font.HELVETICA_BOLD;
	return PDType1Font.HELVETICA;
}
 
Example 24
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   Source Code and License 6 votes vote down vote up
@Override
public void drawText(AttributedCharacterIterator iterator, IFontTextDrawerEnv env)
		throws IOException, FontFormatException {
	PDPageContentStream contentStream = env.getContentStream();

	contentStream.beginText();

	Matrix textMatrix = new Matrix();
	textMatrix.scale(1, -1);
	contentStream.setTextMatrix(textMatrix);

	StringBuilder sb = new StringBuilder();
	boolean run = true;
	while (run) {

		Font attributeFont = (Font) iterator.getAttribute(TextAttribute.FONT);
		if (attributeFont == null)
			attributeFont = env.getFont();

		Number fontSize = ((Number) iterator.getAttribute(TextAttribute.SIZE));
		if (fontSize != null)
			attributeFont = attributeFont.deriveFont(fontSize.floatValue());
		PDFont font = applyFont(attributeFont, env);

		Paint paint = (Paint) iterator.getAttribute(TextAttribute.FOREGROUND);
		if (paint == null)
			paint = env.getPaint();

		/*
		 * Apply the paint
		 */
		env.applyPaint(paint);

		boolean isStrikeThrough = TextAttribute.STRIKETHROUGH_ON
				.equals(iterator.getAttribute(TextAttribute.STRIKETHROUGH));
		boolean isUnderline = TextAttribute.UNDERLINE_ON.equals(iterator.getAttribute(TextAttribute.UNDERLINE));
		boolean isLigatures = TextAttribute.LIGATURES_ON.equals(iterator.getAttribute(TextAttribute.LIGATURES));

		run = iterateRun(iterator, sb);
		String text = sb.toString();

		/*
		 * If we force the text write we may encounter situations where the font can not
		 * display the characters. PDFBox will throw an exception in this case. We will
		 * just silently ignore the text and not display it instead.
		 */
		try {
			showTextOnStream(env, contentStream, attributeFont, font, isStrikeThrough, isUnderline, isLigatures,
					text);
		} catch (IllegalArgumentException e) {
			if (font instanceof PDType1Font && !font.isEmbedded()) {
				/*
				 * We tried to use a builtin default font, but it does not have the needed
				 * characters. So we use a embedded font as fallback.
				 */
				try {
					if (fallbackFontUnknownEncodings == null)
						fallbackFontUnknownEncodings = findFallbackFont(env);
					if (fallbackFontUnknownEncodings != null) {
						env.getContentStream().setFont(fallbackFontUnknownEncodings, attributeFont.getSize2D());
						showTextOnStream(env, contentStream, attributeFont, fallbackFontUnknownEncodings,
								isStrikeThrough, isUnderline, isLigatures, text);
						e = null;
					}
				} catch (IllegalArgumentException ignored) {
					e = ignored;
				}
			}

			if (e != null)
				System.err.println("PDFBoxGraphics: Can not map text " + text + " with font "
						+ attributeFont.getFontName() + ": " + e.getMessage());
		}
	}
	contentStream.endText();
}
 
Example 25
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
	try {
		PDDocument document = new PDDocument();

		PDFont pdArial = PDFontFactory.createDefaultFont();

		File parentDir = new File("target/test/" + dir);
		// noinspection ResultOfMethodCallIgnored
		parentDir.mkdirs();

		BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
		Graphics2D imageGraphics = image.createGraphics();
		exporter.draw(imageGraphics);
		imageGraphics.dispose();
		ImageIO.write(image, "PNG", new File(parentDir, name + ".png"));

		for (Mode m : Mode.values()) {
			PDPage page = new PDPage(PDRectangle.A4);
			document.addPage(page);

			PDPageContentStream contentStream = new PDPageContentStream(document, page);
			PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);
			PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null;
			contentStream.beginText();
			contentStream.setStrokingColor(0, 0, 0);
			contentStream.setNonStrokingColor(0, 0, 0);
			contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
			contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800));
			contentStream.showText("Mode " + m);
			contentStream.endText();
			switch (m) {
			case FontTextIfPossible:
				fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
				fontTextDrawer.registerFont(
						new File("src/test/resources/de/rototor/pdfbox/graphics2d/DejaVuSerifCondensed.ttf"));
				break;
			case DefaultFontText: {
				fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
				fontTextDrawer.registerFont(
						new File("src/test/resources/de/rototor/pdfbox/graphics2d/DejaVuSerifCondensed.ttf"));
				break;
			}
			case ForceFontText:
				fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer();
				fontTextDrawer.registerFont(
						PdfBoxGraphics2DTestBase.class.getResourceAsStream("DejaVuSerifCondensed.ttf"));
				fontTextDrawer.registerFont("Arial", pdArial);
				break;
			case DefaultVectorized:
			default:
				break;
			}

			if (fontTextDrawer != null) {
				pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);
			}

			exporter.draw(pdfBoxGraphics2D);
			pdfBoxGraphics2D.dispose();

			PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
			Matrix matrix = new Matrix();
			matrix.translate(0, 20);
			contentStream.transform(matrix);
			contentStream.drawForm(appearanceStream);

			matrix.scale(1.5f, 1.5f);
			matrix.translate(0, 100);
			contentStream.transform(matrix);
			contentStream.drawForm(appearanceStream);
			contentStream.close();
		}

		document.save(new File(parentDir, name + ".pdf"));
		document.close();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 26
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawerDefaultFontsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDefaultFontMapping() {
	assertEquals(PDType1Font.HELVETICA,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode(Font.DIALOG)));
	assertEquals(PDType1Font.HELVETICA,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode(Font.DIALOG_INPUT)));
	assertEquals(PDType1Font.HELVETICA,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode("Arial")));

	assertEquals(PDType1Font.COURIER,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode(Font.MONOSPACED)));

	assertEquals(PDType1Font.TIMES_ROMAN,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode(Font.SERIF)));

	assertEquals(PDType1Font.ZAPF_DINGBATS,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode("Dingbats")));

	assertEquals(PDType1Font.SYMBOL,
			PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode("Symbol")));

	assertNull(PdfBoxGraphics2DFontTextDrawerDefaultFonts.mapDefaultFonts(Font.decode("Georgia")));
}
 
Example 27
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License 6 votes vote down vote up
public PDDocument getBillAsPdf() throws IOException {
    // Add blank page to document
    PDPage firstPage = new PDPage();
    document.addPage(firstPage);
    PDPageContentStream contentStream = new PDPageContentStream(document, firstPage);
    generateBillHeader(firstPage, contentStream);
    generateBillInfoText(firstPage, contentStream);
    contentStream.beginText();
    contentStream.newLineAtOffset(60f, 640f);

    // Add the column line item header line
    contentStream.setFont(PDType1Font.COURIER_BOLD, NORMAL_FONT_SIZE);
    contentStream.newLine();
    contentStream.showText(lineItemHeader);

    // Add bill line items
    contentStream.setFont(NORMAL_FONT, NORMAL_FONT_SIZE);
    for(String lineItem : lineItems) {
        contentStream.newLine();
        contentStream.showText(lineItem);
    }

    // Display the bill total at the end
    contentStream.newLine();
    String billTotalLine = getBillTotalLine();
    contentStream.setFont(PDType1Font.COURIER_BOLD, NORMAL_FONT_SIZE);
    contentStream.newLine();
    contentStream.showText(billTotalLine);

    // Display important bill information
    contentStream.newLine();
    contentStream.newLine();
    contentStream.showText("WARNING: Failure to pay bill may result in broken legs.");

    contentStream.endText();
    contentStream.close();

    return document;
}
 
Example 28
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 6 votes vote down vote up
@Test
public void mergeFourElementsIntoFourWords() {
	
	List<TextElement> elements = new ArrayList<>();
	elements.add(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(20f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f));
	elements.add(new TextElement(40f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f));
	elements.add(new TextElement(60f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	
	List<TextChunk> words = TextElement.mergeWords(elements);
	
	List<TextChunk> expectedWords = new ArrayList<>();
	expectedWords.add(new TextChunk(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f)));
	expectedWords.add(new TextChunk(new TextElement(20f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f)));
	expectedWords.add(new TextChunk(new TextElement(40f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f)));
	expectedWords.add(new TextChunk(new TextElement(60f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f)));
	
	Assert.assertEquals(expectedWords, words);
	
}
 
Example 29
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 6 votes vote down vote up
@Test
public void mergeElementsShouldBeIdempotent() {
	/*
   * a bug in TextElement.merge_words would delete the first TextElement in the array
   * it was called with. Discussion here: https://github.com/tabulapdf/tabula-java/issues/78
   */

	List<TextElement> elements = new ArrayList<>();
	elements.add(new TextElement(0f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(0f, 25f, 10f, 20f, PDType1Font.HELVETICA, 1f, "B", 1f, 6f));
	elements.add(new TextElement(0f, 35f, 10f, 20f, PDType1Font.HELVETICA, 1f, "C", 1f, 6f));
	elements.add(new TextElement(0f, 45f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	
	List<TextChunk> words = TextElement.mergeWords(elements);
	List<TextChunk> words2 = TextElement.mergeWords(elements);
	Assert.assertEquals(words, words2);
}
 
Example 30
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 6 votes vote down vote up
@Test
public void mergeTenElementsIntoTwoWords() {
	
	List<TextElement> elements = new ArrayList<>();
	elements.add(new TextElement(0f, 0f, 10f, 20f, PDType1Font.HELVETICA, 1f, "H", 1f, 6f));
	elements.add(new TextElement(0f, 10f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	elements.add(new TextElement(0f, 20f, 10f, 20f, PDType1Font.HELVETICA, 1f, "L", 1f, 6f));
	elements.add(new TextElement(0f, 30f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(0f, 60f, 10f, 20f, PDType1Font.HELVETICA, 1f, "M", 1f, 6f));
	elements.add(new TextElement(0f, 70f, 10f, 20f, PDType1Font.HELVETICA, 1f, "U", 1f, 6f));
	elements.add(new TextElement(0f, 80f, 10f, 20f, PDType1Font.HELVETICA, 1f, "N", 1f, 6f));
	elements.add(new TextElement(0f, 90f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	elements.add(new TextElement(0f, 100f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	
	List<TextChunk> words = TextElement.mergeWords(elements);
	
	List<TextChunk> expectedWords = new ArrayList<>();
	TextChunk textChunk = new TextChunk(new TextElement(0f, 0f, 10f, 20f, PDType1Font.HELVETICA, 1f, "H", 1f, 6f));
	textChunk.add(new TextElement(0f, 10f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	textChunk.add(new TextElement(0f, 20f, 10f, 20f, PDType1Font.HELVETICA, 1f, "L", 1f, 6f));
	textChunk.add(new TextElement(0f, 30f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	textChunk.add(new TextElement(0f, 30f, 10.5f, 20f, PDType1Font.HELVETICA, 1f, " ", 1f)); //Check why width=10.5?
	expectedWords.add(textChunk);
	TextChunk textChunk2 = new TextChunk(new TextElement(0f, 60f, 10f, 20f, PDType1Font.HELVETICA, 1f, "M", 1f, 6f));
	textChunk2.add(new TextElement(0f, 70f, 10f, 20f, PDType1Font.HELVETICA, 1f, "U", 1f, 6f));
	textChunk2.add(new TextElement(0f, 80f, 10f, 20f, PDType1Font.HELVETICA, 1f, "N", 1f, 6f));
	textChunk2.add(new TextElement(0f, 90f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	textChunk2.add(new TextElement(0f, 100f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	expectedWords.add(textChunk2);
	
	Assert.assertEquals(2, words.size());
	Assert.assertEquals(expectedWords, words);
	
}
 
Example 31
Project: 484_P7_1-Java   File: TestTextElement.java   Source Code and License 6 votes vote down vote up
@Test
public void mergeTenElementsIntoTwoLines() {
	
	List<TextElement> elements = new ArrayList<>();
	elements.add(new TextElement(0f, 0f, 10f, 20f, PDType1Font.HELVETICA, 1f, "H", 1f, 6f));
	elements.add(new TextElement(0f, 10f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	elements.add(new TextElement(0f, 20f, 10f, 20f, PDType1Font.HELVETICA, 1f, "L", 1f, 6f));
	elements.add(new TextElement(0f, 30f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	elements.add(new TextElement(20f, 0f, 10f, 20f, PDType1Font.HELVETICA, 1f, "M", 1f, 6f));
	elements.add(new TextElement(20f, 10f, 10f, 20f, PDType1Font.HELVETICA, 1f, "U", 1f, 6f));
	elements.add(new TextElement(20f, 20f, 10f, 20f, PDType1Font.HELVETICA, 1f, "N", 1f, 6f));
	elements.add(new TextElement(20f, 30f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	elements.add(new TextElement(20f, 40f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	
	List<TextChunk> words = TextElement.mergeWords(elements);
	
	List<TextChunk> expectedWords = new ArrayList<>();
	TextChunk textChunk = new TextChunk(new TextElement(0f, 0f, 10f, 20f, PDType1Font.HELVETICA, 1f, "H", 1f, 6f));
	textChunk.add(new TextElement(0f, 10f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	textChunk.add(new TextElement(0f, 20f, 10f, 20f, PDType1Font.HELVETICA, 1f, "L", 1f, 6f));
	textChunk.add(new TextElement(0f, 30f, 10f, 20f, PDType1Font.HELVETICA, 1f, "A", 1f, 6f));
	expectedWords.add(textChunk);
	TextChunk textChunk2 = new TextChunk(new TextElement(20f, 0f, 10f, 20f, PDType1Font.HELVETICA, 1f, "M", 1f, 6f));
	textChunk2.add(new TextElement(20f, 10f, 10f, 20f, PDType1Font.HELVETICA, 1f, "U", 1f, 6f));
	textChunk2.add(new TextElement(20f, 20f, 10f, 20f, PDType1Font.HELVETICA, 1f, "N", 1f, 6f));
	textChunk2.add(new TextElement(20f, 30f, 10f, 20f, PDType1Font.HELVETICA, 1f, "D", 1f, 6f));
	textChunk2.add(new TextElement(20f, 40f, 10f, 20f, PDType1Font.HELVETICA, 1f, "O", 1f, 6f));
	expectedWords.add(textChunk2);
	
	Assert.assertEquals(2, words.size());
	Assert.assertEquals(expectedWords, words);
	
}
 
Example 32
Project: ctsms   File: PDFUtil.java   Source Code and License 6 votes vote down vote up
public static PDFont loadFont(String fontFileName, PDDocument doc, PDFont defaultBaseFont) throws IOException {
	// public static PDFont loadFont(String fontFileName, PDDocument doc, PDFont defaultBaseFont, PDStream pdStream) throws IOException {
	PDFont font = null;
	if (fontFileName != null && fontFileName.length() > 0) {
		font = PDType1Font.getStandardFont(fontFileName);
		if (font == null) {
			font = PDTrueTypeFont.loadTTF(doc, fontFileName);
			// http://stackoverflow.com/questions/5570225/workaround-for-pdfbox-pdtruetypefont-bad-widths-bug
		}
	} else {
		font = defaultBaseFont;
	}
	// if (font != null && pdStream != null) {
	// if (font instanceof PDType1Font) {
	// ((PDType1Font) font).setToUnicode(pdStream.getCOSObject());
	// } else if (font instanceof PDTrueTypeFont) {
	// ((PDTrueTypeFont) font).setToUnicode(pdStream.getCOSObject());
	// }
	// }
	return font;
}
 
Example 33
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License 6 votes vote down vote up
private PDPage generateAttendeePage(Attendee attendee, PDDocument document) throws IOException {
    PDPage page = new PDPage(new PDRectangle(612f, 396f));
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Positions are measured from the bottom left corner of the page at 72 DPI

    // Set up global transformation matrix according to xOffset, yOffset.
    // NOTE: if we want to support per-printer/per-client scaling, we would replace the 1's
    // below, with xScale and yScale.
    contentStream.concatenate2CTM(1, 0, 0, 1, xOffset, yOffset);

    // Draw fields on badge depending on badge type
    drawStaffNames(contentStream, attendee);
    drawBadgeNumber(contentStream, attendee);
    drawAgeColorStripe(contentStream, font, attendee);
    drawBadgeType(contentStream, attendee);
    contentStream.close();

    return page;
}
 
Example 34
Project: AwesomeJavaLibraryExamples   File: ExampleAddImage.java   Source Code and License 6 votes vote down vote up
private static void createOverlayDocument(File overlayPdf) throws IOException
{
   PDDocument overlayDoc = new PDDocument();

   try
   {
      PDPage page=new PDPage();

      overlayDoc.addPage(page);
      PDFont font=PDType1Font.COURIER_OBLIQUE;

      PDPageContentStream contentStream=new PDPageContentStream(overlayDoc, page);
      contentStream.setFont(font, 50);
      contentStream.setNonStrokingColor(0);
      contentStream.beginText();
      contentStream.newLineAtOffset(100, 500);
      contentStream.setNonStrokingColor(255, 0, 0);
      contentStream.showText("CLASSIFIED");
      contentStream.endText();
      contentStream.close();
      overlayDoc.save(overlayPdf);
   }
   finally
   {
      overlayDoc.close();
   }
}
 
Example 35
Project: AwesomeJavaLibraryExamples   File: ExampleHelloPdf.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException
{
   PDDocument doc = new PDDocument();
   File pdfFile = File.createTempFile("devict-example", ".pdf");

   try
   {
      PDPage page = new PDPage();
      doc.addPage(page);

      PDFont font = PDType1Font.HELVETICA_BOLD;

      PDPageContentStream contents = new PDPageContentStream(doc, page);
      contents.beginText();
      contents.setFont(font, 12);
      contents.newLineAtOffset(100, 700);
      contents.showText("Hello DevICT PDFBox the time is " + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
      contents.endText();
      contents.close();

      doc.save(pdfFile);
   }
   finally
   {
      System.out.printf("PDF created and saved at %s\n", pdfFile.getAbsolutePath());
      doc.close();
   }

   Desktop.getDesktop().open(pdfFile);
}
 
Example 36
Project: pcm-api   File: PdfBoxHandler.java   Source Code and License 6 votes vote down vote up
private static Map<PdfBoxFont, PDFont> buildPDFontMap() {
    return Collections.unmodifiableMap(Stream.of(
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_ROMAN, PDType1Font.TIMES_ROMAN),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_BOLD, PDType1Font.TIMES_BOLD),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_ITALIC, PDType1Font.TIMES_ITALIC),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_BOLD_ITALIC, PDType1Font.TIMES_BOLD_ITALIC),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA, PDType1Font.HELVETICA),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA_BOLD, PDType1Font.HELVETICA_BOLD),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA_OBLIQUE, PDType1Font.HELVETICA_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA_BOLD_OBLIQUE, PDType1Font.HELVETICA_BOLD_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER, PDType1Font.COURIER),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER_BOLD, PDType1Font.COURIER_BOLD),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER_OBLIQUE, PDType1Font.COURIER_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER_BOLD_OBLIQUE, PDType1Font.COURIER_BOLD_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.SYMBOL, PDType1Font.SYMBOL),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.ZAPF_DINGBATS, PDType1Font.ZAPF_DINGBATS))
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)));
}
 
Example 37
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addConsentTitle(String titleMessageKey, float startYCoordinate, PDPage page, PDPageContentStream contentStream) throws IOException {
    String consentTitle = getI18nMessage(titleMessageKey);

    float titleFontSize = 20f;
    PDFont titleFont = PDType1Font.TIMES_BOLD;
    Color titleColor = Color.BLACK;
    float width = page.getMediaBox().getWidth() - 2 * PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    pdfBoxService.addWrappedParagraph(consentTitle, titleFont, titleFontSize, titleColor, TextAlignment.LEFT, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, startYCoordinate, width, page, contentStream);
}
 
Example 38
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addConsentReferenceNumberAndPatientInfo(Consent consent, Patient patient, float startYCoordinate, PDFont defaultFont, PDPageContentStream contentStream) throws IOException {
    String consentCreatedOn = PdfBoxHandler.formatDate(consent.getCreatedDateTime(), DATE_FORMAT_PATTERN);
    String consentReferenceNumber = consent.getConsentReferenceId();
    String patientFullName = patient.getFirstName().concat(SPACE_PATTERN + patient.getLastName());
    String patientBirthDate = PdfBoxHandler.formatDate(patient.getBirthDay(), DATE_FORMAT_PATTERN);

    final Color textColor = Color.BLACK;
    final float fontSize = PdfBoxStyle.TEXT_SMALL_SIZE;
    final PDFont contentFont = PDType1Font.TIMES_BOLD;

    // Add Consent Created On
    final String createdOnLabel = getI18nMessage("REVOCATION.PDF.DATE");
    pdfBoxService.addTextAtOffset(createdOnLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, startYCoordinate, contentStream);
    final float createdOnXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(createdOnLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(consentCreatedOn, contentFont, fontSize, textColor, createdOnXCoordinate, startYCoordinate, contentStream);

    // Add Consent Reference Number
    final float crnLabelYCoordinate = startYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    final String crnLabel = getI18nMessage("CONSENT.REFERENCE.NUMBER");
    pdfBoxService.addTextAtOffset(crnLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, crnLabelYCoordinate, contentStream);
    final float crnYCoordinate = crnLabelYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    pdfBoxService.addTextAtOffset(consentReferenceNumber, contentFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, crnYCoordinate, contentStream);

    // Add patient name
    final float nameYCoordinate = crnYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    final String nameLabel = getI18nMessage("PATIENT.NAME");
    pdfBoxService.addTextAtOffset(nameLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, nameYCoordinate, contentStream);
    final float nameXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(nameLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(patientFullName, contentFont, fontSize, textColor, nameXCoordinate, nameYCoordinate, contentStream);

    // Add patient DOB
    final String dobLabel = getI18nMessage("PATIENT.DOB");
    final float dobLabelXCoordinate = 310f;
    pdfBoxService.addTextAtOffset(dobLabel, defaultFont, fontSize, textColor, dobLabelXCoordinate, nameYCoordinate, contentStream);
    final float dobXCoordinate = dobLabelXCoordinate + PdfBoxHandler.targetedStringWidth(dobLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(patientBirthDate, contentFont, fontSize, textColor, dobXCoordinate, nameYCoordinate, contentStream);
}
 
Example 39
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addConsentSigningDetails(Patient patient, Date signedOnDateTime, float startYCoordinate, PDFont defaultFont, PDPageContentStream contentStream) throws IOException {
    String patientName = patient.getFirstName().concat(SPACE_PATTERN + patient.getLastName());
    String email = patient.getEmail();

    final String signedByLabel = getI18nMessage("SIGNED.BY");
    final String emailLabel = getI18nMessage("EMAIL");
    final String signedOnLabel = getI18nMessage("SIGNED.ON");

    final PDFont contentFont = PDType1Font.TIMES_BOLD;
    final Color textColor = Color.BLACK;
    final float fontSize = PdfBoxStyle.TEXT_SMALL_SIZE;

    // Add Signed by
    pdfBoxService.addTextAtOffset(signedByLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, startYCoordinate, contentStream);
    final float crnXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(signedByLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(patientName, contentFont, fontSize, textColor, crnXCoordinate, startYCoordinate, contentStream);

    // Add Email
    final float emailYCoordinate = startYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    pdfBoxService.addTextAtOffset(emailLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, emailYCoordinate, contentStream);
    final float nameXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(emailLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(email, contentFont, fontSize, textColor, nameXCoordinate, emailYCoordinate, contentStream);

    // Add Signed on
    final float signedOnYCoordinate = emailYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    pdfBoxService.addTextAtOffset(signedOnLabel, defaultFont, fontSize, textColor, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, signedOnYCoordinate, contentStream);
    final float dobXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER + PdfBoxHandler.targetedStringWidth(signedOnLabel, defaultFont, fontSize);
    pdfBoxService.addTextAtOffset(PdfBoxHandler.formatDate(signedOnDateTime, DATE_FORMAT_PATTERN), contentFont, fontSize, textColor, dobXCoordinate, signedOnYCoordinate, contentStream);
}
 
Example 40
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addMedicalInformation(Consent consent, float labelYCoordinate, PDFont font, PDPageContentStream contentStream) throws IOException {
    final float xCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    final float listWidth = 286f;
    final String itemMarkerSymbol = "-";
    float subLabelYCoordinate = labelYCoordinate - 15f;
    float listYCoordinate = labelYCoordinate - 20f;
    String label = getI18nMessage("CONSENT.PDF.CATEGORY.TITLE");
    String subLabel = getI18nMessage("SENSITIVE.CATEGORY");

    pdfBoxService.addTextAtOffset(label, PDType1Font.TIMES_BOLD, PdfBoxStyle.TEXT_SMALL_SIZE, Color.BLACK, xCoordinate, labelYCoordinate, contentStream);
    pdfBoxService.addTextAtOffset(subLabel, font, PdfBoxStyle.TEXT_SMALL_SIZE, Color.BLACK, xCoordinate, subLabelYCoordinate, contentStream);

    List<String> sensitivityCategories = getMedicalInformation(consent);

    pdfBoxService.addUnorderedListContent(sensitivityCategories, itemMarkerSymbol, xCoordinate, listYCoordinate, listWidth, font, PdfBoxStyle.TEXT_SMALL_SIZE, contentStream);
}
 
Example 41
Project: testarea-pdfbox2   File: TestEmptySignatureField.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/37601092/pdfbox-identify-specific-pages-and-functionalities-recommendations">
 * PDFBox identify specific pages and functionalities recommendations
 * </a>
 * 
 * <p>
 * This test shows how to add an empty signature field with a custom appearance
 * to an existing PDF.
 * </p>
 */
@Test
public void testAddEmptySignatureField() throws IOException
{
    try (   InputStream sourceStream = getClass().getResourceAsStream("test.pdf");
            OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "test-with-empty-sig-field.pdf")))
    {
        PDFont font = PDType1Font.HELVETICA;
        PDResources resources = new PDResources();
        resources.put(COSName.getPDFName("Helv"), font);

        PDDocument document = PDDocument.load(sourceStream);
        PDAcroForm acroForm = new PDAcroForm(document);
        acroForm.setDefaultResources(resources);
        document.getDocumentCatalog().setAcroForm(acroForm);

        PDRectangle rect = new PDRectangle(50, 750, 200, 50);

        PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
        PDAppearanceStream appearanceStream = new PDAppearanceStream(document);
        appearanceStream.setBBox(rect.createRetranslatedRectangle());
        appearanceStream.setResources(resources);
        appearanceDictionary.setNormalAppearance(appearanceStream);
        PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream);
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
        contentStream.setLineWidth(2);
        contentStream.addRect(0, 0, rect.getWidth(), rect.getHeight());
        contentStream.fill();
        contentStream.moveTo(1 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.lineTo(2 * rect.getHeight() / 4, 3 * rect.getHeight() / 4);
        contentStream.moveTo(1 * rect.getHeight() / 4, 3 * rect.getHeight() / 4);
        contentStream.lineTo(2 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.moveTo(3 * rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.lineTo(rect.getWidth() - rect.getHeight() / 4, 1 * rect.getHeight() / 4);
        contentStream.stroke();
        contentStream.setNonStrokingColor(Color.DARK_GRAY);
        contentStream.beginText();
        contentStream.setFont(font, rect.getHeight() / 5);
        contentStream.newLineAtOffset(3 * rect.getHeight() / 4, -font.getBoundingBox().getLowerLeftY() * rect.getHeight() / 5000);
        contentStream.showText("Customer");
        contentStream.endText();
        contentStream.close();

        PDSignatureField signatureField = new PDSignatureField(acroForm);
        signatureField.setPartialName("SignatureField");
        PDPage page = document.getPage(0);

        PDAnnotationWidget widget = signatureField.getWidgets().get(0);
        widget.setAppearance(appearanceDictionary);
        widget.setRectangle(rect);
        widget.setPage(page);

        page.getAnnotations().add(widget);
        acroForm.getFields().add(signatureField);

        document.save(output);
        document.close();
    }
}
 
Example 42
Project: testarea-pdfbox2   File: TextAndGraphics.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/44503236/how-to-write-text-draw-a-line-and-then-again-write-text-in-a-pdf-file-using-pdf">
 * How to write text, draw a line and then again write text in a pdf file using PDFBox
 * </a>
 * <p>
 * This test shows how to draw tetx, then graphics, then again text.
 * </p>
 */
@Test
public void testDrawTextLineText() throws IOException
{
    PDFont font = PDType1Font.HELVETICA;
    float fontSize = 14;
    float fontHeight = fontSize;
    float leading = 20;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    Date date = new Date();

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);

    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
    contentStream.setFont(font, fontSize);

    float yCordinate = page.getCropBox().getUpperRightY() - 30;
    float startX = page.getCropBox().getLowerLeftX() + 30;
    float endX = page.getCropBox().getUpperRightX() - 30;

    contentStream.beginText();
    contentStream.newLineAtOffset(startX, yCordinate);
    contentStream.showText("Entry Form � Header");
    yCordinate -= fontHeight;  //This line is to track the yCordinate
    contentStream.newLineAtOffset(0, -leading);
    yCordinate -= leading;
    contentStream.showText("Date Generated: " + dateFormat.format(date));
    yCordinate -= fontHeight;
    contentStream.endText(); // End of text mode

    contentStream.moveTo(startX, yCordinate);
    contentStream.lineTo(endX, yCordinate);
    contentStream.stroke();
    yCordinate -= leading;

    contentStream.beginText();
    contentStream.newLineAtOffset(startX, yCordinate);
    contentStream.showText("Name: XXXXX");
    contentStream.endText();

    contentStream.close();
    doc.save(new File(RESULT_FOLDER, "textLineText.pdf"));
}
 
Example 43
Project: common-libraries   File: PdfBoxHandler.java   Source Code and License 6 votes vote down vote up
private static Map<PdfBoxFont, PDFont> buildPDFontMap() {
    return Collections.unmodifiableMap(Stream.of(
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_ROMAN, PDType1Font.TIMES_ROMAN),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_BOLD, PDType1Font.TIMES_BOLD),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_ITALIC, PDType1Font.TIMES_ITALIC),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.TIMES_BOLD_ITALIC, PDType1Font.TIMES_BOLD_ITALIC),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA, PDType1Font.HELVETICA),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA_BOLD, PDType1Font.HELVETICA_BOLD),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA_OBLIQUE, PDType1Font.HELVETICA_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.HELVETICA_BOLD_OBLIQUE, PDType1Font.HELVETICA_BOLD_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER, PDType1Font.COURIER),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER_BOLD, PDType1Font.COURIER_BOLD),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER_OBLIQUE, PDType1Font.COURIER_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.COURIER_BOLD_OBLIQUE, PDType1Font.COURIER_BOLD_OBLIQUE),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.SYMBOL, PDType1Font.SYMBOL),
            new AbstractMap.SimpleEntry<>(PdfBoxFont.ZAPF_DINGBATS, PDType1Font.ZAPF_DINGBATS))
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)));
}
 
Example 44
Project: common-libraries   File: Footer.java   Source Code and License 6 votes vote down vote up
/**
 * Sole constructor.
 * Return a footer in gray TIMES_BOLD, sz 8.
 * The left part of the text is todays date, 
 * center is username, 
 * and the right part is PAGENUM of NUMPAGES
 */
public Footer() {
    textColor = Color.gray;
    leftText = Footer.DATE;
    centerText = Footer.USER;
    rightText = "Page " + Footer.PAGENUM + " of " + Footer.NUMPAGES;
    OMIT_FIRSTPAGE = true;
    COUNT_FIRSTPAGE = true;
    font = PDType1Font.TIMES_BOLD;
    fontsize = 8;
}
 
Example 45
Project: common-libraries   File: Footer.java   Source Code and License 6 votes vote down vote up
public Footer(String leftText, String centerTextStr, String rightTextStr ) {
    textColor = Color.gray;
    leftText = Footer.DATE;
    centerText = centerTextStr;
    rightText = rightTextStr;
    OMIT_FIRSTPAGE = true;
    COUNT_FIRSTPAGE = true;
    font = PDType1Font.TIMES_BOLD;
    fontsize = 8;
}
 
Example 46
Project: common-libraries   File: HexPdf.java   Source Code and License 6 votes vote down vote up
/**
 * Sole constructor, creates a new instance of HexPdf.
 */
public HexPdf() {
    super();
    this.ignorePagebleed = false;
    this.numPages = 0;
    this.rightMargin = 50f;
    this.leftMargin = 50f;
    this.bottomMargin = 50f;
    this.topMargin = 50f;
    this.fontSize = 10;
    this.font = PDType1Font.TIMES_ROMAN;
    this.pageSize = PDRectangle.A4;
    this.normalColor = Color.black;
    this.titleColor = Color.black;
    this.orientation = HexPdf.PORTRAIT;
    //firstPage();
}
 
Example 47
Project: kumoreg   File: FullBadgePrintFormatter.java   Source Code and License 6 votes vote down vote up
private PDPage generateAttendeePage(Attendee attendee, PDDocument document) throws IOException {
    PDPage page = new PDPage(new PDRectangle(612f, 396f));
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Positions are measured from the bottom left corner of the page at 72 DPI

    // Set up global transformation matrix according to xOffset, yOffset.
    // NOTE: if we want to support per-printer/per-client scaling, we would replace the 1's
    // below, with xScale and yScale.
    contentStream.concatenate2CTM(1, 0, 0, 1, xOffset, yOffset);

    // Draw fields on badge depending on badge type
    drawStaffNames(contentStream, attendee);
    drawBadgeNumber(contentStream, attendee);
    drawAgeColorStripe(contentStream, font, attendee);
    drawBadgeType(contentStream, attendee);
    contentStream.close();

    return page;
}
 
Example 48
Project: icecite   File: PdfStreamEngine.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the CharMetric for the glyph given by glyphName. 
 * 
 * @param glyphName the name of glyph.
 * @param type1Font the font.
 * @return the CharMetric.
 */
protected CharMetric getCharMetric(String glyphName, PDType1Font type1Font) 
    throws IOException {
  if (type1Font != null) {
    String basename = PdfFontUtil.computeBasename(type1Font);
    
    if (this.additionalAFMs == null) {
      this.additionalAFMs = readAdditionalAFMFiles("afm/");
    }
    
    FontMetricsWrapper fontMetrics = this.additionalAFMs.get(basename);
    if (fontMetrics != null) {
      return fontMetrics.getCharMetricsMap().get(glyphName);
    }
  }
  return null;
}
 
Example 49
Project: icecite   File: PdfFontUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test the computeBasename() method.
 */
@Test
public void testComputeBasename() {
  Assert.assertEquals(null, PdfFontUtil.computeBasename(null));
  
  String result = PdfFontUtil.computeBasename(PDType1Font.COURIER);
  Assert.assertEquals("courier", result);
  
  result = PdfFontUtil.computeBasename(PDType1Font.HELVETICA_OBLIQUE);
  Assert.assertEquals("helvetica-oblique", result);
  
  result = PdfFontUtil.computeBasename(PDType1Font.SYMBOL);
  Assert.assertEquals("symbol", result);
  
  result = PdfFontUtil.computeBasename(PDType1Font.TIMES_BOLD_ITALIC);
  Assert.assertEquals("times-bolditalic", result);

}
 
Example 50
Project: testarea-pdfbox1   File: PdfRenderingEndorsement.java   Source Code and License 6 votes vote down vote up
/**
 * Renders the header for slip documents.
 */
public void rHeader() throws Exception {
float y = 760f;
content.setLineWidth(.5f);
content.setFont(PDType1Font.TIMES_ROMAN, 9);
content.setNonStrokingColor(Color.GRAY);
content.drawLine(50, 710, 562, 710);

y = rText(150, y + 19, 10, "ENDOSO" /*constants.endorsement()*/, null,
      TEXT_WIDTH, 0);
y = rText(150, y + 9, 10, header[0], null, TEXT_WIDTH, 0);
y = rText(150, y + 9, 10, header[1], null, TEXT_WIDTH, 0);
y = rText(150, y + 9, 10, header[2], null, TEXT_WIDTH, 0);
y = rText(150, y + 9, 10, header[3], null, TEXT_WIDTH, 0);
content.setNonStrokingColor(Color.BLACK);
content.setFont(PDType1Font.TIMES_ROMAN, 9);
}
 
Example 51
Project: testarea-pdfbox1   File: PdfRenderingEndorsement.java   Source Code and License 6 votes vote down vote up
public float rText(float x, float y, int space, String labelField,
           String value, int fieldWidth, int valueWidth) 
throws Exception {
PDFont font = PDType1Font.TIMES_BOLD;
content.setFont(font, 9);
float y1 = 0f;
float y2 = 0f;
if (value == null) {
    return rText(labelField, fieldWidth, x, y - 19, space, font, false);
} else {
    if (labelField == null) {
    font = PDType1Font.TIMES_ROMAN;
    content.setFont(font, 9);
    return rText(value, valueWidth, x, y - 19, space, font, true);
    } else {
    y1 = rText(labelField, fieldWidth, x, y - 30, space, font, 
           false);
    font = PDType1Font.TIMES_ROMAN;
    content.setFont(font, 9);
    float y3 = y;
    y2 = rText(value, valueWidth, x + fieldWidth + 10, y - 30,
           space, font, true);
    if (y3 < y2) {
        return y2;
    } else {
        if (y1 >= y2) {
        return y2;
        } else {
        return y1;
        }
    }
    }
}
}
 
Example 52
Project: testarea-pdfbox1   File: PdfRenderingSimple.java   Source Code and License 6 votes vote down vote up
public void renderText(String Info, int marginwidth) throws IOException
{
    if (content == null || textRenderingLineY < 12)
        newPage();

    textRenderingLineY-=12;    
    System.out.print("lineno=" + textRenderingLineY);
    PDFont fontPlain = PDType1Font.HELVETICA;
    content.beginText();
    content.setFont(fontPlain, 10);
    content.moveTextPositionByAmount(marginwidth, textRenderingLineY);
    content.drawString(Info);
    content.endText();
}
 
Example 53
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/22260344/pdfbox-encode-symbol-currency-euro">
 * PdfBox encode symbol currency euro
 * </a>
 * <p>
 * Three ways of trying to draw a '�' symbol, the first one fails.
 * </p>
 */
@Test
public void testDrawEuro() throws IOException, COSVisitorException
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDPageContentStream contents = new PDPageContentStream(document, page);
    PDFont font = PDType1Font.HELVETICA_BOLD;
    contents.beginText();
    contents.setFont(font, 18);
    contents.moveTextPositionByAmount(30, 600);
    contents.drawString("�");
    contents.moveTextPositionByAmount(0, -30);
    contents.drawString(String.valueOf(Character.toChars(EncodingManager.INSTANCE.getEncoding(COSName.WIN_ANSI_ENCODING).getCode("Euro"))));
    contents.moveTextPositionByAmount(0, -30);
    byte[] commands = "(x) Tj ".getBytes();
    commands[1] = (byte) 128;
    contents.appendRawCommands(commands);
    contents.endText();
    contents.close();
    document.save(new File(RESULT_FOLDER, "Euro.pdf"));
    document.close();
}
 
Example 54
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
/**
    * <a href="http://stackoverflow.com/questions/30619974/pdfbox-unable-to-write-superscripted-characters">
    * PDFBox unable to write superscripted characters
    * </a>
    * <p>
    * {@link #testDrawTmSignBroken()} represents the observation the OP made,
    * {@link #testDrawTmSignCustomDraw()} is a solution using custom drawing operations, and
    * {@link #testDrawTmSignLetters()} is a solution drawing the trademark symbol using smaller letters with text rise.
    * </p>
    */
@Test
public void testDrawTmSignBroken() throws IOException, COSVisitorException
{
	PDDocument document = new PDDocument();
       PDPage page = new PDPage();
       document.addPage(page);
       PDPageContentStream contents = new PDPageContentStream(document, page);
       PDFont font = PDType1Font.HELVETICA_BOLD;
       contents.beginText();
       contents.setFont(font, 18);
       contents.moveTextPositionByAmount(30, 600);
       contents.drawString("90000039-PREDISOL � C YELLOW 13 SNDOT�M");
       contents.endText();
       contents.close();
       document.save(new File(RESULT_FOLDER, "TM_naive.pdf"));
       document.close();
}
 
Example 55
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
@Test
public void testDrawTmSignCustomDraw() throws IOException, COSVisitorException
{
	PDDocument document = new PDDocument();
       PDPage page = new PDPage();
       document.addPage(page);
       PDPageContentStream contents = new PDPageContentStream(document, page);
       PDFont font = PDType1Font.HELVETICA_BOLD;
       contents.beginText();
       contents.setFont(font, 18);
       contents.moveTextPositionByAmount(30, 600);
       contents.drawString("90000039-PREDISOL � C YELLOW 13 SNDOT");
       byte[] commands = "(x) Tj ".getBytes();
       commands[1] = (byte) 0231;
       contents.appendRawCommands(commands);
       contents.drawString("M");
       contents.endText();
       contents.close();
       document.save(new File(RESULT_FOLDER, "TM_customDraw.pdf"));
       document.close();
}
 
Example 56
Project: testarea-pdfbox1   File: DrawSpecialCharacters.java   Source Code and License 6 votes vote down vote up
@Test
public void testDrawTmSignLetters() throws IOException, COSVisitorException
{
	PDDocument document = new PDDocument();
       PDPage page = new PDPage();
       document.addPage(page);
       PDPageContentStream contents = new PDPageContentStream(document, page);
       PDFont font = PDType1Font.HELVETICA_BOLD;
       contents.beginText();
       contents.setFont(font, 18);
       contents.moveTextPositionByAmount(30, 600);
       contents.drawString("90000039-PREDISOL � C YELLOW 13 SNDOT");
       contents.appendRawCommands("\n6 Ts\n".getBytes());
       contents.setFont(font, 10);
       contents.drawString("TM");
       contents.appendRawCommands("\n0 Ts\n".getBytes());
       contents.setFont(font, 18);
       contents.drawString("M");
       contents.endText();
       contents.close();
       document.save(new File(RESULT_FOLDER, "TM_letters.pdf"));
       document.close();
}
 
Example 57
Project: testarea-pdfbox1   File: InsertPages.java   Source Code and License 6 votes vote down vote up
public PDDocument create1Page(String mark) throws IOException
{
    PDDocument document = new PDDocument();
    
    PDPage page = new PDPage();
    document.addPage(page);
    PDPageContentStream content = new PDPageContentStream(document, page);
    content.beginText();
    content.setFont(PDType1Font.HELVETICA_BOLD, 100);
    content.moveTextPositionByAmount(100, 300);
    content.drawString(mark);
    content.endText();
    content.close();
    
    return document;
}
 
Example 58
Project: tudoToPDF   File: DummyPDFConverter.java   Source Code and License 6 votes vote down vote up
@Override
public File convertPDF(File theFile, String md5UploadedFile) throws PDFConverterException {

	try {
		PDDocument document = new PDDocument();
		PDPage page = new PDPage();
		document.addPage(page);
		PDFont font = PDType1Font.HELVETICA_BOLD;
		PDPageContentStream contentStream = new PDPageContentStream(document, page);
		contentStream.beginText();
		contentStream.setFont(font, 12);
		contentStream.newLineAtOffset(100, 700);
		contentStream.showText("This is a test PDF file.");
		contentStream.endText();
		contentStream.close();
		String outFileName = this.getOutputFileName(md5UploadedFile);
		File outputFile = new File(Config.getString("application.staticFiles"), outFileName);
		document.save(outputFile);
		document.close();
		return outputFile;
	} catch (Exception e) {
		log.error("Fail to create dummy PDF", e);
		throw new PDFConverterException(e);
	}

}
 
Example 59
Project: CSSBoxPdf   File: PDFRenderer.java   Source Code and License 6 votes vote down vote up
private PDFont tryBuiltinFallback(String fontFamily, boolean isItalic, boolean isBold)
{
    PDFont font;
    
    fontFamily = fontFamily.toLowerCase();
    switch (fontFamily) {
    case "courier":
    case "courier new":
    case "lucida console":
        if (isBold && isItalic) { font = PDType1Font.COURIER_BOLD_OBLIQUE;}
        else if (isBold) { font = PDType1Font.COURIER_BOLD;}
        else if (isItalic) { font = PDType1Font.COURIER_OBLIQUE;}
        else { font = PDType1Font.COURIER;}
        break;
    case "times":
    case "garamond":
    case "georgia":
    case "times new roman":
    case "serif":
        if (isBold && isItalic) { font = PDType1Font.TIMES_BOLD_ITALIC;}
        else if (isBold) { font = PDType1Font.TIMES_BOLD;}
        else if (isItalic) { font = PDType1Font.TIMES_ITALIC;}
        else { font = PDType1Font.TIMES_ROMAN;}
        break;
    default:
        if (isBold && isItalic) { font = PDType1Font.HELVETICA_BOLD_OBLIQUE;}
        else if (isBold) { font = PDType1Font.HELVETICA_BOLD;}
        else if (isItalic) { font = PDType1Font.HELVETICA_OBLIQUE;}
        else { font = PDType1Font.HELVETICA;}
        break;
    }
    return font;
}
 
Example 60
Project: tabula-java   File: TestProjectionProfile.java   Source Code and License 6 votes vote down vote up
@Before
public void setUpProjectionProfile() {
	PDPage pdPage = new PDPage();
	
	TextElement textElement = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "test", 1f);
	TextElement textElement2 = new TextElement(5f, 15f, 10f, 20f, PDType1Font.HELVETICA, 1f, "test", 1f);
	List<TextElement> textList = new ArrayList<>();
	textList.add(textElement);
	textList.add(textElement2);

	Ruling ruling = new Ruling(0, 0, 10, 10);
	List<Ruling> rulingList = new ArrayList<>();
	rulingList.add(ruling);


	page = new Page(0, 0, 1, 1, 0, 1, pdPage, textList, rulingList);
	
	List<Rectangle> rectangles = new ArrayList<>();
	rectangles.add(new Rectangle(0f, 0f, 500f, 5f));
	
	pProfile = new ProjectionProfile(page, rectangles, 5, 5);
}