Java Code Examples for org.apache.pdfbox.pdmodel.PDPageContentStream#showText()

The following examples show how to use org.apache.pdfbox.pdmodel.PDPageContentStream#showText() . 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: VerticalTextCellDrawer.java    From easytable with MIT License 6 votes vote down vote up
protected void drawText(String text, PDFont font, int fontSize, Color color, float x, float y, PDPageContentStream contentStream) throws IOException {
    // Rotate by 90 degrees counter clockwise
    final AffineTransform transform = AffineTransform.getTranslateInstance(x, y);
    transform.concatenate(AffineTransform.getRotateInstance(Math.PI * 0.5));
    transform.concatenate(AffineTransform.getTranslateInstance(-x, -y - fontSize));

    contentStream.moveTo(x, y);
    contentStream.beginText();

    // Do the transformation :)
    contentStream.setTextMatrix(transform);

    contentStream.setNonStrokingColor(color);
    contentStream.setFont(font, fontSize);
    contentStream.newLineAtOffset(x, y);
    contentStream.showText(text);
    contentStream.endText();
    contentStream.setCharacterSpacing(0);
}
 
Example 2
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void writeText(PDPageContentStream contentStream, Color color, PDFont font, float fontSize, boolean rotate, float x, float y, String... text)
		throws IOException {
	contentStream.beginText();
	// set font and font size
	contentStream.setFont(font, fontSize);
	// set text color
	contentStream.setNonStrokingColor(color.getRed(), color.getGreen(), color.getBlue());
	if (rotate) {
		// rotate the text according to the page rotation
		contentStream.setTextMatrix(Matrix.getRotateInstance(Math.PI / 2, x, y));
	} else {
		contentStream.setTextMatrix(Matrix.getTranslateInstance(x, y));
	}
	if (text.length > 1) {
		contentStream.setLeading(25f);

	}
	for (String line : text) {
		contentStream.showText(line);
		contentStream.newLine();
	}
	contentStream.endText();
}
 
Example 3
Source File: ShowSpecialGlyph.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49426018/%e2%82%b9-indian-rupee-symbol-symbol-is-printing-as-question-mark-in-pdf-using-apa">
 * ₹ (Indian Rupee Symbol) symbol is printing as ? (question mark) in pdf using Apache PDFBOX
 * </a>
 * <p>
 * This test shows how to successfully show the Indian Rupee symbol
 * based on the OP's source frame and Tilman's proposed font.
 * </p>
 */
@Test
public void testIndianRupeeForVandanaSharma() throws IOException {
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream cos=  new PDPageContentStream(doc, page);
    cos.beginText();
    String text = "Deposited Cash of ₹10,00,000/- or more in a Saving Bank Account";
    cos.newLineAtOffset(25, 700);
    cos.setFont(PDType0Font.load(doc, new File("c:/windows/fonts/arial.ttf")), 12);
    cos.showText(text);
    cos.endText();
    cos.close();
    doc.save(new File(RESULT_FOLDER, "IndianRupee.pdf"));
    doc.close();
}
 
Example 4
Source File: JoinPages.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareBiggerPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A5);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.GREEN);
    contentStream.addRect(0, 0, PDRectangle.A5.getWidth(), PDRectangle.A5.getHeight());
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDType1Font.HELVETICA;
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, PDRectangle.A5.getHeight() - 24);
    contentStream.showText("This is the Bigger page");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("BIGGER!");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example 5
Source File: PdfManipulator.java    From estatio with Apache License 2.0 6 votes vote down vote up
private float addLines(
        final float x, final float y,
        final float height,
        final List<Line> lines,
        final PDPageContentStream cs) throws IOException {
    cs.setFont(TEXT_FONT, TEXT_FONT_SIZE);
    float yLine = y + height - TEXT_LINE_HEIGHT;
    for (Line line : lines) {

        cs.setNonStrokingColor(line.color);
        cs.beginText();
        cs.newLineAtOffset(x + TEXT_X_PADDING, yLine);
        cs.showText(line.text);
        cs.endText();

        yLine -= TEXT_LINE_HEIGHT;
    }

    return yLine;
}
 
Example 6
Source File: RotatedTextOnLine.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/52054396/rotate-text-in-pdfbox-with-java">
 * Rotate text in pdfbox with java
 * </a>
 * <p>
 * This test shows how to show rotated text above a line.
 * </p>
 */
@Test
public void testRotatedTextOnLineForCedrickKapema() throws IOException {
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream cos = new PDPageContentStream(doc, page);
    cos.transform(Matrix.getRotateInstance(-Math.PI / 6, 100, 650));
    cos.moveTo(0, 0);
    cos.lineTo(125, 0);
    cos.stroke();
    cos.beginText();
    String text = "0.72";
    cos.newLineAtOffset(50, 5);
    cos.setFont(PDType1Font.HELVETICA_BOLD, 12);
    cos.showText(text);
    cos.endText();
    cos.close();
    doc.save(new File(RESULT_FOLDER, "TextOnLine.pdf"));
    doc.close();
}
 
Example 7
Source File: HelloWorldFont.java    From blog-codes with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	// Create a document and add a page to it
	PDDocument document = new PDDocument();
	PDPage page = new PDPage();
	document.addPage( page );

	// Create a new font object selecting one of the PDF base fonts
	PDFont font = PDType1Font.HELVETICA_BOLD;

	// Start a new content stream which will "hold" the to be created content
	PDPageContentStream contentStream = new PDPageContentStream(document, page);

	// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
	contentStream.beginText();
	contentStream.setFont( font, 12 );
	contentStream.newLineAtOffset( 100, 700 );
	contentStream.showText( "Hello World" );
	contentStream.endText();

	// Make sure that the content stream is closed:
	contentStream.close();

	// Save the results and ensure that the document is properly closed:
	document.save( "/home/lili/data/Hello World.pdf");
	document.close();

}
 
Example 8
Source File: GradeElementRenderer.java    From PDF4Teachers with Apache License 2.0 5 votes vote down vote up
public void renderElement(GradeElement element, PDPageContentStream contentStream, PDPage page, float pageWidth, float pageHeight, float pageRealWidth, float pageRealHeight, float startX, float startY) throws IOException {

        if(!element.isVisible()) return;

        // COLOR
        Color color = element.getColor();
        contentStream.setNonStrokingColor(new java.awt.Color((float) color.getRed(), (float) color.getGreen(), (float) color.getBlue(), (float) color.getOpacity()));

        // FONT
        boolean bold = false;
        if (FontUtils.getFontWeight(element.getFont()) == FontWeight.BOLD) bold = true;
        boolean italic = false;
        if (FontUtils.getFontPosture(element.getFont()) == FontPosture.ITALIC) italic = true;
        InputStream fontFile = FontUtils.getFontFile(element.getFont().getFamily(), italic, bold);
        element.setFont(FontUtils.getFont(element.getFont().getFamily(), italic, bold, element.getFont().getSize() / 596.0 * pageWidth));

        contentStream.beginText();

        // CUSTOM STREAM

        Map.Entry<String, String> entry = Map.entry(element.getFont().getFamily(), FontUtils.getFontFileName(italic, bold));

        if(!fonts.containsKey(entry)){
            PDType0Font font = PDType0Font.load(doc, fontFile);
            contentStream.setFont(font, (float) element.getFont().getSize());
            fonts.put(entry, font);
        }else{
            contentStream.setFont(fonts.get(entry), (float) element.getFont().getSize());
        }

        float bottomMargin = pageRealHeight-pageHeight-startY;
        contentStream.newLineAtOffset(startX + element.getRealX() / Element.GRID_WIDTH * pageWidth, bottomMargin + pageRealHeight - element.getBaseLineY() - element.getRealY() / Element.GRID_HEIGHT * pageHeight);
        try{
            contentStream.showText(element.getText());
        }catch(IllegalArgumentException e){
            e.printStackTrace();
            System.err.println("Erreur : impossible d'écrire la note : \"" + element.getText() + "\" avec la police " + element.getFont().getFamily());
            System.err.println("Message d'erreur : " + e.getMessage());
        }
        contentStream.endText();

    }
 
Example 9
Source File: DrawingUtil.java    From easytable with MIT License 5 votes vote down vote up
public static void drawText(PDPageContentStream contentStream, PositionedStyledText styledText) throws IOException {
    contentStream.beginText();
    contentStream.setNonStrokingColor(styledText.getColor());
    contentStream.setFont(styledText.getFont(), styledText.getFontSize());
    contentStream.newLineAtOffset(styledText.getX(), styledText.getY());
    contentStream.showText(styledText.getText());
    contentStream.endText();
    contentStream.setCharacterSpacing(0);
}
 
Example 10
Source File: DashboardUtil.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * Footer is filled with varaibles selected in Grafana by user
 * 
 * @param doc
 * @param title
 * @param variables
 * @return doc
 * @throws IOException
 */
private PDDocument footer(PDDocument doc, String title, String variables) throws IOException {
	try{
		PDPageTree pages = doc.getPages();
		for(PDPage p : pages){
			PDPageContentStream contentStream = new PDPageContentStream(doc, p, AppendMode.APPEND, false);
			contentStream.beginText();
			contentStream.newLineAtOffset(220, 780);
			contentStream.setFont(PDType1Font.HELVETICA, 11);
			contentStream.showText("OneDevOps Insights – "+title);
			contentStream.endText();
			if(!variables.equals("") && variables != null){
				contentStream.beginText();
				contentStream.newLineAtOffset(2, 17);
				contentStream.setFont(PDType1Font.HELVETICA, 9);
				contentStream.showText("This Report is generated based on the user selected values as below.");
				contentStream.endText();
				contentStream.beginText();
				contentStream.newLineAtOffset(2, 5);
				contentStream.setFont(PDType1Font.HELVETICA, 7);
				contentStream.showText(variables);
				contentStream.endText();
			}
			contentStream.close();
		}
	}catch(Exception e){
		Log.error("Error, Failed in Footer.. ", e.getMessage());
	}
	return doc;
}
 
Example 11
Source File: PDFPage.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param contentStream
 * @param text
 */
public static void securedShowText(PDPageContentStream contentStream, String text) {
	try {
		contentStream.showText(remove(text));
	} catch (Exception e) {
		throw new RuntimeException("Error in printing text " + text + ", original exception "
				+ e.getClass().toString() + " = " + e.getMessage());
	}
}
 
Example 12
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Generate the appearance for comb fields.
 * 
 * @param contents the content stream to write to
 * @param appearanceStream the appearance stream used
 * @param font the font to be used
 * @param fontSize the font size to be used
 * @throws IOException
 */
private void insertGeneratedCombAppearance(PDPageContentStream contents, PDAppearanceStream appearanceStream,
        PDFont font, float fontSize) throws IOException
{
    
    // TODO:    Currently the quadding is not taken into account
    //          so the comb is always filled from left to right.
    
    int maxLen = ((PDTextField) field).getMaxLen();
    int numChars = Math.min(value.length(), maxLen);
    
    PDRectangle paddingEdge = applyPadding(appearanceStream.getBBox(), 1);
    
    float combWidth = appearanceStream.getBBox().getWidth() / maxLen;
    float ascentAtFontSize = font.getFontDescriptor().getAscent() / FONTSCALE * fontSize;
    float baselineOffset = paddingEdge.getLowerLeftY() +  
            (appearanceStream.getBBox().getHeight() - ascentAtFontSize)/2;
    
    float prevCharWidth = 0f;
    
    float xOffset = combWidth / 2;

    for (int i = 0; i < numChars; i++) 
    {
        String combString = value.substring(i, i+1);
        float currCharWidth = font.getStringWidth(combString) / FONTSCALE * fontSize/2;
        
        xOffset = xOffset + prevCharWidth/2 - currCharWidth/2;
        
        contents.newLineAtOffset(xOffset, baselineOffset);
        contents.showText(combString);
        
        baselineOffset = 0;
        prevCharWidth = currCharWidth;
        xOffset = combWidth;
    }
}
 
Example 13
Source File: ArrangeText.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/48902656/how-can-i-align-arrange-text-fields-into-two-column-layout-using-apache-pdfbox">
 * How can I Align/ Arrange text fields into two column layout using Apache PDFBox - java
 * </a>
 * <p>
 * This test shows how to align text in two columns.
 * </p>
 */
@Test
public void testArrangeTextForUser2967784() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDFont fontNormal = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream =new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.newLineAtOffset(100, 600);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("Name: ");
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("Rajeev");
    contentStream.newLineAtOffset(200, 00);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("Address: " );
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("BNG");
    contentStream.newLineAtOffset(-200, -20);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("State: " );
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("KAR");
    contentStream.newLineAtOffset(200, 00);
    contentStream.setFont(fontBold, 15);
    contentStream.showText("Country: " );
    contentStream.setFont(fontNormal, 15);
    contentStream.showText ("INDIA");
    contentStream.endText();
    contentStream.close();
    document.save(new File(RESULT_FOLDER, "arrangedTextForUser2967784.pdf"));
}
 
Example 14
Source File: CompatibilityHelper.java    From pdfbox-layout with MIT License 4 votes vote down vote up
public static void showText(final PDPageContentStream contentStream,
    final String text) throws IOException {
contentStream.showText(text);
   }
 
Example 15
Source File: TextAndGraphics.java    From testarea-pdfbox2 with Apache License 2.0 4 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 16
Source File: AddTextWithDynamicFonts.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
public void show(PDPageContentStream canvas, float fontSize) throws IOException {
    canvas.setFont(font, fontSize);
    canvas.showText(text);
}
 
Example 17
Source File: TestEmptySignatureField.java    From testarea-pdfbox2 with Apache License 2.0 4 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 = Loader.loadPDF(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 18
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Draws a custom text with the specified parameters
 * @param cs
 *		{@link PDPageContentStream} current stream
 * @param dimensionAndPosition
 *		{@link SignatureFieldDimensionAndPosition} size and position to place the text to
 * @param textParameters
 *		{@link SignatureImageTextParameters} text to place on the signature field
 * @throws IOException
 *		in case of error
 */
private void setText(PDPageContentStream cs, SignatureFieldDimensionAndPosition dimensionAndPosition, 
		SignatureImageParameters parameters) throws IOException {
	SignatureImageTextParameters textParameters = parameters.getTextParameters();
   	if (textParameters != null && Utils.isStringNotEmpty(textParameters.getText())) {
   		setTextBackground(cs, textParameters, dimensionAndPosition);
   		DSSFont dssFont = textParameters.getFont();
           float fontSize = dssFont.getSize();
           fontSize *= ImageUtils.getScaleFactor(parameters.getZoom());
           cs.beginText();
           cs.setFont(pdFont, fontSize);
           cs.setNonStrokingColor(textParameters.getTextColor());
           setAlphaChannel(cs, textParameters.getTextColor());
           
           PdfBoxFontMetrics pdfBoxFontMetrics = new PdfBoxFontMetrics(pdFont);
           
           String[] strings = pdfBoxFontMetrics.getLines(textParameters.getText());
           
           float properSize = CommonDrawerUtils.computeProperSize(textParameters.getFont().getSize(), parameters.getDpi());
           
           float fontHeight = pdfBoxFontMetrics.getHeight(textParameters.getText(), properSize);
           cs.setLeading(textSizeWithDpi(fontHeight, dimensionAndPosition.getyDpi()));
           
           cs.newLineAtOffset(dimensionAndPosition.getTextX(),
           		// align vertical position
           		dimensionAndPosition.getTextHeight() + dimensionAndPosition.getTextY() - fontSize);

           float previousOffset = 0;
           for (String str : strings) {
               float stringWidth = pdfBoxFontMetrics.getWidth(str, fontSize);
               float offsetX = 0;
               switch (textParameters.getSignerTextHorizontalAlignment()) {
				case RIGHT:
					offsetX = dimensionAndPosition.getTextWidth() - stringWidth - 
							textSizeWithDpi(textParameters.getPadding()*2, dimensionAndPosition.getxDpi()) - previousOffset;
					break;
				case CENTER:
					offsetX = (dimensionAndPosition.getTextWidth() - stringWidth) / 2 - 
							textSizeWithDpi(textParameters.getPadding(), dimensionAndPosition.getxDpi()) - previousOffset;
					break;
				default:
					break;
			}
               previousOffset += offsetX;
			cs.newLineAtOffset(offsetX, 0); // relative offset
               cs.showText(str);
               cs.newLine();
           }
           cs.endText();
           cleanTransparency(cs);
   	}
}
 
Example 19
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private void insertGeneratedListboxAppearance(PDPageContentStream contents, PDAppearanceStream appearanceStream,
        PDRectangle contentRect, PDFont font, float fontSize) throws IOException
{
    contents.setNonStrokingColor(0);
    
    int q = field.getQ();

    if (q == PDVariableText.QUADDING_CENTERED || q == PDVariableText.QUADDING_RIGHT)
    {
        float fieldWidth = appearanceStream.getBBox().getWidth();
        float stringWidth = (font.getStringWidth(value) / FONTSCALE) * fontSize;
        float adjustAmount = fieldWidth - stringWidth - 4;

        if (q == PDVariableText.QUADDING_CENTERED)
        {
            adjustAmount = adjustAmount / 2.0f;
        }

        contents.newLineAtOffset(adjustAmount, 0);
    }
    else if (q != PDVariableText.QUADDING_LEFT)
    {
        throw new IOException("Error: Unknown justification value:" + q);
    }

    List<String> options = ((PDListBox) field).getOptionsDisplayValues();
    int numOptions = options.size();

    float yTextPos = contentRect.getUpperRightY();

    int topIndex = ((PDListBox) field).getTopIndex();
    
    for (int i = topIndex; i < numOptions; i++)
    {
       
        if (i == topIndex)
        {
            yTextPos = yTextPos - font.getFontDescriptor().getAscent() / FONTSCALE * fontSize;
        }
        else
        {
            yTextPos = yTextPos - font.getBoundingBox().getHeight() / FONTSCALE * fontSize;
            contents.beginText();
        }

        contents.newLineAtOffset(contentRect.getLowerLeftX(), yTextPos);
        contents.showText(options.get(i));

        if (i != (numOptions - 1))
        {
            contents.endText();
        }
    }
}
 
Example 20
Source File: PDFGenerator.java    From scim2-compliance-test-suite with Apache License 2.0 3 votes vote down vote up
/**
 * Print the results to PDF.
 * @param contentStream
 * @param fontSize
 * @param pdfFont
 * @param leading
 * @param startX
 * @param startY
 * @param lines
 * @throws IOException
 */
public static void printResult(PDPageContentStream contentStream, float fontSize,
                               PDFont pdfFont, float leading, float startX, float startY, List<String> lines)
        throws IOException {
    for (String line : lines) {
        contentStream.showText(line);
        contentStream.newLineAtOffset(0, -leading);
    }
}