Java Code Examples for org.apache.pdfbox.pdmodel.PDPage

The following are top voted examples for showing how to use org.apache.pdfbox.pdmodel.PDPage. 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 12 votes vote down vote up
@Test
public void createAlternateRowsDocument() throws Exception {
    final PDDocument document = new PDDocument();
    final PDPage page = new PDPage(PDRectangle.A4);
    page.setRotation(90);
    document.addPage(page);
    final PDPageContentStream contentStream = new PDPageContentStream(document, page);
    // TODO replace deprecated method call
    contentStream.concatenate2CTM(0, 1, -1, 0, page.getMediaBox().getWidth(), 0);
    final float startY = page.getMediaBox().getWidth() - 30;

    (new TableDrawer(contentStream, createAndGetTableWithAlternatingColors(), 30, startY)).draw();
    contentStream.close();

    document.save("target/alternateRows.pdf");
    document.close();
}
 
Example 2
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License 10 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 3
Project: 484_P7_1-Java   File: NurminenDetectionAlgorithm.java   Source Code and License 10 votes vote down vote up
private PDDocument removeText(PDPage page) throws IOException {

        PDFStreamParser parser = new PDFStreamParser(page);
        parser.parse();
        List<Object> tokens = parser.getTokens();
        List<Object> newTokens = new ArrayList<>();
        for (Object token : tokens) {
            if (token instanceof Operator) {
                Operator op = (Operator) token;
                if (op.getName().equals("TJ") || op.getName().equals("Tj")) {
                    //remove the one argument to this operator
                    newTokens.remove(newTokens.size() - 1);
                    continue;
                }
            }
            newTokens.add(token);
        }

        PDDocument document = new PDDocument();
        document.addPage(page);

        PDStream newContents = new PDStream(document);
        OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE);
        ContentStreamWriter writer = new ContentStreamWriter(out);
        writer.writeTokens(newTokens);
        out.close();
        page.setContents(newContents);

        return document;

    }
 
Example 4
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License 10 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
 * Render Type3 font character as image using PDFBox
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
 * 4700198773.pdf
 * </a>
 * from
 * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
 * extract text with custom font result non readble
 * </a>
 * <p>
 * This test shows how one can render individual Type 3 font glyphs as bitmaps.
 * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
 * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
 * with the glyph in question and render that page.   
 * </p>
 * <p>
 * As the OP did not provide a sample PDF, we simply use one from another
 * stackoverflow question. There obviously might remain issues with the
 * OP's files.
 * </p>
 */
@Test
public void testRenderSdnList() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("sdnlist.pdf"))
    {
        PDDocument document = PDDocument.load(resource);

        PDPage page = document.getPage(1);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("R144");
        PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
        Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

        COSDictionary charProcsDictionary = fontF1.getCharProcs();
        for (COSName key : charProcsDictionary.keySet())
        {
            COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
            PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
            PDRectangle bbox = charProc.getGlyphBBox();
            if (bbox == null)
                bbox = charProc.getBBox();
            Integer code = f1NameToCode.get(key.getName());

            if (code != null)
            {
                PDDocument charDocument = new PDDocument();
                PDPage charPage = new PDPage(bbox);
                charDocument.addPage(charPage);
                charPage.setResources(pageResources);
                PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                charContentStream.beginText();
                charContentStream.setFont(fontF1, bbox.getHeight());
                charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
                charContentStream.endText();
                charContentStream.close();

                File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code));
                PDFRenderer renderer = new PDFRenderer(charDocument);
                BufferedImage image = renderer.renderImageWithDPI(0, 96);
                ImageIO.write(image, "PNG", result);
                charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 5
Project: kumoreg   File: ReportPrintFormatter.java   Source Code and License 9 votes vote down vote up
private PDPage generatePage(String[] lines, int startAt, PDDocument document) throws IOException {
    PDPage page = new PDPage(new PDRectangle(612f, 396f));
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

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

    // Add report text to page
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(36+xOffset, 360+yOffset);
    contentStream.setFont(font, fontSize);
    int lineNumber = startAt;
    while (lineNumber < startAt + linesPerPage && lineNumber < lines.length) {
        contentStream.drawString(lines[lineNumber]);
        contentStream.moveTextPositionByAmount(0, (-1*fontSize));
        lineNumber += 1;
    }
    contentStream.endText();

    contentStream.close();

    return page;

}
 
Example 6
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 7
Project: BoxTable   File: Table.java   Source Code and License 8 votes vote down vote up
/**
 * Renders this table to a document
 * 
 * @param document
 *            The document this table will be rendered to
 * @param width
 *            The width of the table
 * @param left
 *            The left edge of the table
 * @param top
 *            The top edge of the table
 * @param paddingTop
 *            The amount of free space at the top of a new page (if a page break is necessary)
 * @param paddingBottom
 *            The minimal amount of free space at the bottom of the page before inserting a page break
 * @return The bottom edge of the last rendered table part
 * @throws IOException
 *             If writing to the document fails
 */
@SuppressWarnings("resource")
public float render(final PDDocument document, final float width, final float left, float top, final float paddingTop, final float paddingBottom)
		throws IOException {
	float yPos = top;
	final PDPage page = document.getPage(document.getNumberOfPages() - 1);
	final PDRectangle pageSize = page.getMediaBox();
	PDPageContentStream stream = new PDPageContentStream(document, page, AppendMode.APPEND, true);
	float height = getHeight(width);
	if (height > pageSize.getHeight() - paddingTop - paddingBottom) {
		final float[] colWidths = getColumnWidths(width);
		for (int i = 0; i < rows.size(); ++i) {
			if (rows.get(i).getHeight(colWidths) > yPos - paddingBottom) {
				drawBorder(stream, left, top, width, top - yPos);
				stream = newPage(document, stream);
				top = pageSize.getHeight() - paddingTop;
				yPos = top;
				yPos = renderRows(document, stream, 0, getNumHeaderRows(), width, left, yPos);
				i = Math.max(i, getNumHeaderRows());
			}
			yPos = renderRows(document, stream, i, i + 1, width, left, yPos);
		}
		drawBorder(stream, left, top, width, top - yPos);

		handleEvent(EventType.AFTER_TABLE, document, stream, left, top, width, top - yPos);
	} else {
		if (height > top - paddingBottom) {
			stream = newPage(document, stream);
			top = pageSize.getHeight() - paddingTop;
			yPos = top;
		}
		yPos = renderRows(document, stream, 0, -1, width, left, yPos);
		drawBorder(stream, left, top, width, top - yPos);
		handleEvent(EventType.AFTER_TABLE, document, stream, left, top, width, top - yPos);
	}
	stream.close();

	return yPos;
}
 
Example 8
Project: pdfbox-graphics2d   File: MultiPageTest.java   Source Code and License 8 votes vote down vote up
@Test
public void testMultiPageJFreeChart() throws IOException {
	File parentDir = new File("target/test/multipage");
	// noinspection ResultOfMethodCallIgnored
	parentDir.mkdirs();
	File targetPDF = new File(parentDir, "multipage.pdf");
	PDDocument document = new PDDocument();
	for (int i = 0; i < 4; i++) {
		PDPage page = new PDPage(PDRectangle.A4);
		document.addPage(page);

		PDPageContentStream contentStream = new PDPageContentStream(document, page);
		PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 800, 400);
		drawOnGraphics(pdfBoxGraphics2D, i);
		pdfBoxGraphics2D.dispose();

		PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
		Matrix matrix = new Matrix();
		matrix.translate(0, 30);
		matrix.scale(0.7f, 1f);

		contentStream.saveGraphicsState();
		contentStream.transform(matrix);
		contentStream.drawForm(appearanceStream);
		contentStream.restoreGraphicsState();

		contentStream.close();
	}
	document.save(targetPDF);
	document.close();
}
 
Example 9
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 10
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 11
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 8 votes vote down vote up
@Override
public void addWrappedParagraph(String text, PDFont font, float fontSize, Color textColor, TextAlignment align, float xCoordinate, float topYCoordinate, float width, PDPage page, PDPageContentStream contentStream) throws IOException {
    Paragraph paragraph = new Paragraph(text, width, font, fontSize);

    final float lineSpacing = 1.2f * fontSize;
    PDRectangle region = page.getMediaBox();

    contentStream.beginText();
    contentStream.setFont(font, fontSize);
    contentStream.setNonStrokingColor(textColor);
    for (String line : paragraph.getLines()) {
        if (align == TextAlignment.CENTER) {
            float stringWidth = PdfBoxHandler.targetedStringWidth(line, font, fontSize);
            float centerXPos = (region.getWidth() - stringWidth) / 2f;
            contentStream.setTextTranslation(centerXPos, region.getHeight() - topYCoordinate);
        } else {
            contentStream.setTextTranslation(xCoordinate, region.getHeight() - topYCoordinate);
        }
        contentStream.showText(line);
        topYCoordinate += lineSpacing;
    }
    contentStream.endText();
    resetChangedColorToDefault(contentStream);
}
 
Example 12
Project: testarea-pdfbox2   File: RemoveStrikeoutComment.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45812696/pdfbox-delete-comment-maintain-strikethrough">
 * PDFBox delete comment maintain strikethrough
 * </a>
 * <br/>
 * <a href="https://expirebox.com/files/3d955e6df4ca5874c38dbf92fc43b5af.pdf">
 * only_fields.pdf
 * </a>
 * <a href="https://file.io/DTvqhC">
 * (alternative download)
 * </a>
 * <p>
 * The OP only wanted the comment removed, not the strike-through. Thus, we must
 * not remove the annotation but merely the comment building attributes.
 * </p>
 */
@Test
public void testRemoveLikeStephanImproved() throws IOException {
    final COSName POPUP = COSName.getPDFName("Popup");
    try (InputStream resource = getClass().getResourceAsStream("only_fields.pdf")) {
        PDDocument document = PDDocument.load(resource);
        List<PDAnnotation> annotations = new ArrayList<>();
        PDPageTree allPages = document.getDocumentCatalog().getPages();

        List<COSObjectable> objectsToRemove = new ArrayList<>();

        for (int i = 0; i < allPages.getCount(); i++) {
            PDPage page = allPages.get(i);
            annotations = page.getAnnotations();

            for (PDAnnotation annotation : annotations) {
                if ("StrikeOut".equals(annotation.getSubtype()))
                {
                    COSDictionary annotationDict = annotation.getCOSObject();
                    COSBase popup = annotationDict.getItem(POPUP);
                    annotationDict.removeItem(POPUP);
                    annotationDict.removeItem(COSName.CONTENTS); // plain text comment
                    annotationDict.removeItem(COSName.RC);       // rich text comment
                    annotationDict.removeItem(COSName.T);        // author

                    if (popup != null)
                        objectsToRemove.add(popup);
                }
            }

            annotations.removeAll(objectsToRemove);
        }

        document.save(new File(RESULT_FOLDER, "only_fields-removeImproved.pdf"));
    }
}
 
Example 13
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 8 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box.
 * </p>
 */
@Test
public void testRotateCenter() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); 
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center.pdf"));
    }
}
 
Example 14
Project: PrintDF   File: BookletMaker.java   Source Code and License 7 votes vote down vote up
/**
 * Creates a pdf page from two pages from another 'original' pdf document
 * @param doc original pdf from which the pages will be taken
 * @param leftPage page number of the page to go on the left side 
 * @param rightPage page number of the page to go on the right side
 * @return generated page containing the left and right pages from the original document side-by-side.
 */
private static PDPage createBookPage(PDDocument doc, int leftPage, int rightPage) {
	// double the width of a normal page to create the booklet
	PDRectangle baseSize = doc.getPage(0).getMediaBox();		
	PDRectangle box = new PDRectangle(baseSize.getWidth()*2, baseSize.getHeight());
	

	if(sizeOverride != null) {
		box = sizeOverride.asPDRectangle();
	}
	
	PDPage page = new PDPage(box);
	
	try {
		PDImageXObject leftImg = PrintDF.pageToImage(doc, leftPage, scale);
		PDImageXObject rightImg = PrintDF.pageToImage(doc, rightPage, scale);
		
		
		
		PDPageContentStream contentStream = new PDPageContentStream(doc, page);
		if(leftImg != null)
			contentStream.drawImage(leftImg, 0, 0, box.getWidth()/2, box.getHeight());
		if(rightImg != null)
			contentStream.drawImage(rightImg, box.getWidth()/2, 0, box.getWidth()/2, box.getHeight());
		contentStream.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return page;
}
 
Example 15
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 16
Project: git-rekt   File: BillPdfGenerator.java   Source Code and License 7 votes vote down vote up
private float getCenteredTextXPos(PDPage page, String text, PDFont font, int fontSize)
        throws IOException {
    float textWidth = getStringWidth(text, font, fontSize);
    PDRectangle pageSize = page.getMediaBox();
    float pageCenterX = pageSize.getWidth() / 2F;
    float textX = pageCenterX - textWidth/2F;
    return textX;
}
 
Example 17
Project: IDBuilderFX   File: ExtractPhoto.java   Source Code and License 7 votes vote down vote up
public static void findPhoto(String path,int empId) throws IOException, SQLException, Error{
		// Loading an existing document
		int imageFound=0;
		File file = new File(path);
		PDDocument document=PDDocument.load(file);
		PDPageTree list=document.getPages();
		for(PDPage page:list){						//check in all pages of pdf
			PDResources pdResources=page.getResources();		//get all resources
			for(COSName cosName:pdResources.getXObjectNames())		//loop for all resources
			{
				PDXObject pdxObject=pdResources.getXObject(cosName);
				 if (pdxObject instanceof PDImageXObject) {			//check that the resource is image
		                BufferedImage br=((PDImageXObject) pdxObject).getImage();
		                RgbImage im = RgbImageJ2se.toRgbImage(br);
		                // step #3 - convert image to greyscale 8-bits
		                RgbAvgGray toGray = new RgbAvgGray();
		                toGray.push(im);
		                // step #4 - initialize face detector with correct Haar profile
		                InputStream is  = ExtractPhoto.class.getResourceAsStream("/haar/HCSB.txt");
		                Gray8DetectHaarMultiScale detectHaar = new Gray8DetectHaarMultiScale(is, 1,40);
		                // step #5 - apply face detector to grayscale image
		                List<Rect> result= detectHaar.pushAndReturn(toGray.getFront());
		                if(result.size()!=0)
		                {
		                database.StorePhoto.storePhoto(empId,br);
		                imageFound=1;
		                break;
		                }
				 }
			}
			if(imageFound==1)
				break;
}
		System.out.println(imageFound);
		if(imageFound!=1){
			BufferedImage in = ImageIO.read(ExtractPhoto.class.getResource("/images/nopic.jpg"));
            database.StorePhoto.storePhoto(empId,in);
		}
	document.close();	
	}
 
Example 18
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 19
Project: ctsms   File: PDFImprinter.java   Source Code and License 7 votes vote down vote up
private PDPageContentStream openContentStream(PDPage page, boolean setPageSize, boolean applyPageOrientation) throws IOException {
	contentStream = new PDPageContentStream(doc, page, true, false);
	if (painter != null) {
		PDRectangle pageSize = page.findMediaBox();
		if (PageOrientation.LANDSCAPE.equals(painter.getPageOrientation())) {
			if (setPageSize) {
				painter.setPageHeight(pageSize.getWidth());
				painter.setPageWidth(pageSize.getHeight());
			}
			if (applyPageOrientation) {
				contentStream.concatenate2CTM(0, 1, -1, 0, pageSize.getWidth(), 0); // cos(theta) sin(theta) -sin(theta) cos(theta) 0 0 cm
			}
		} else {
			if (setPageSize) {
				painter.setPageHeight(pageSize.getHeight());
				painter.setPageWidth(pageSize.getWidth());
			}
		}
	}
	return contentStream;
}
 
Example 20
Project: Gargoyle   File: SimpleTextPDFHelpeBuilder.java   Source Code and License 7 votes vote down vote up
public void drawText(PDPage page, PDPageContentStream contentStream, String _text) throws IOException {

		String text = _text;
		//		contentStream.beginText();
		//		contentStream.setFont(getDefaultFont(), 12);
		//		contentStream.newLine();
		//		contentStream.newLineAtOffset(100, 700);
		//		contentStream.showText(this.text);
		//		contentStream.endText();

		float fontSize = 25;
		float leading = 1.5f * fontSize;

		PDRectangle mediabox = page.getMediaBox();
		float margin = 72;
		float width = mediabox.getWidth() - 2 * margin;
		float startX = mediabox.getLowerLeftX() + margin;
		float startY = mediabox.getUpperRightY() - margin;

		int lastSpace = -1;
		while (text.length() > 0) {

			int spaceIndex = text.indexOf(' ', lastSpace + 1);//text.indexOf("\n", lastSpace + 1);
			if (spaceIndex < 0) {
				spaceIndex = text.length();
			}

			String subString = text.substring(0, spaceIndex);
			float size = fontSize * getDefaultFont().getStringWidth(subString) / 1000;
			LOGGER.debug("'{}' - {} of {}\n", subString, size, width);
			if (size > width) {

				if (lastSpace < 0)
					lastSpace = spaceIndex;

				subString = text.substring(0, lastSpace);
				lines.add(subString);
				text = text.substring(lastSpace).trim();
				LOGGER.debug("'{}' is line\n", subString);
				lastSpace = -1;
			} else if (spaceIndex == text.length()) {
				lines.add(text);
				LOGGER.debug("'{}' is line\n", text);
				text = "";
			} else {
				lastSpace = spaceIndex;
			}
		}

		contentStream.beginText();
		contentStream.setFont(getDefaultFont(), fontSize);
		contentStream.newLineAtOffset(startX, startY);
		for (String line : lines) {
			contentStream.showText(line);
			contentStream.newLineAtOffset(0, -leading);
		}
		contentStream.endText();

	}
 
Example 21
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 7 votes vote down vote up
private void drawAgeImageFront(PDPage page, Attendee attendee) throws IOException {

        String imageFilename = BadgeLib.getStaffAgeImageFilename(attendee, currentDateForAgeCalculation);
        if (imageFilename == null) { return; }

        PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);

        PDImageXObject xImage = PDImageXObject.createFromFile(imageFilename, document);
        Dimension scaledDim = getScaledDimension(
                new Dimension(xImage.getWidth(),  xImage.getHeight()),
                new Dimension(149, 130));
        stream.drawImage(xImage,
                45 + ((149-scaledDim.width)/2),
                335 + ((158-scaledDim.height)/2),
                scaledDim.width, scaledDim.height);
        stream.close();
    }
 
Example 22
Project: OSCAR-ConCert   File: SplitDocumentAction.java   Source Code and License 7 votes vote down vote up
public ActionForward rotate180(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	Document doc = documentDao.getDocument(request.getParameter("document"));

	String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");

	FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
	PDFParser parser = new PDFParser(input);
	parser.parse();
	PDDocument pdf = parser.getPDDocument();
	int x = 1;
	for (Object p : pdf.getDocumentCatalog().getAllPages()) {
		PDPage pg = (PDPage)p;
		Integer r = (pg.getRotation() != null ? pg.getRotation() : 0);
		pg.setRotation((r+180)%360);

		ManageDocumentAction.deleteCacheVersion(doc, x);
		x++;
	}

	pdf.save(docdownload + doc.getDocfilename());
	pdf.close();

	input.close();

	return null;
}
 
Example 23
Project: OSCAR-ConCert   File: SplitDocumentAction.java   Source Code and License 7 votes vote down vote up
public ActionForward rotate90(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	Document doc = documentDao.getDocument(request.getParameter("document"));

	String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");

	FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
	PDFParser parser = new PDFParser(input);
	parser.parse();
	PDDocument pdf = parser.getPDDocument();
	int x = 1;
	for (Object p : pdf.getDocumentCatalog().getAllPages()) {
		PDPage pg = (PDPage)p;
		Integer r = (pg.getRotation() != null ? pg.getRotation() : 0);
		pg.setRotation((r+90)%360);

		ManageDocumentAction.deleteCacheVersion(doc, x);
		x++;
	}

	pdf.save(docdownload + doc.getDocfilename());
	pdf.close();

	input.close();

	return null;
}
 
Example 24
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 7 votes vote down vote up
private void addProviderDisclosureIsMadeTo(Consent consent, List<Column> tableColumns, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    String label = getI18nMessage("CONSENT.PDF.SECTION1.CONTENT2");
    addAuthorizationTableHeader(label, startYCoordinate, tableColumns, font, contentStream);

    // To providers details
    final float toProviderDetailsYCoordinate = 342f;
    Set<OrganizationalProvider> fromOrganizations = consent.getOrganizationalProvidersDisclosureIsMadeTo().stream()
            .map(ConsentOrganizationalProviderDisclosureIsMadeTo::getOrganizationalProvider)
            .collect(Collectors.toSet());

    Set<IndividualProvider> fromPractitioners = consent.getProvidersDisclosureIsMadeTo().stream()
            .map(ConsentIndividualProviderDisclosureIsMadeTo::getIndividualProvider)
            .collect(Collectors.toSet());

    addConsentProvidersDetails(fromOrganizations, fromPractitioners, tableColumns, toProviderDetailsYCoordinate, page, contentStream);
}
 
Example 25
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 26
Project: testarea-pdfbox2   File: SetCropBox.java   Source Code and License 7 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39689004/pdfbox-2-0-3-set-cropbox-using-textposition-coordinates">
 * PDFBox 2.0.3 Set cropBox using TextPosition coordinates
 * </a>
 * <br/>
 * <a href="http://downloadcenter.samsung.com/content/UM/201504/20150407095631744/ENG-US_NMATSCJ-1.103-0330.pdf">
 * ENG-US_NMATSCJ-1.103-0330.pdf
 * </a>
 * <p>
 * This test shows how to set the crop box on page twelve and render the cropped page as image.
 * </p>
 */
@Test
public void testSetCropBoxImgENG_US_NMATSCJ_1_103_0330() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("ENG-US_NMATSCJ-1.103-0330.pdf"))
    {
        PDDocument pdDocument = PDDocument.load(resource);
        PDPage page = pdDocument.getPage(12-1);
        page.setCropBox(new PDRectangle(40f, 680f, 510f, 100f));

        PDFRenderer renderer = new PDFRenderer(pdDocument);
        BufferedImage img = renderer.renderImage(12 - 1, 4f);
        ImageIOUtil.writeImage(img, new File(RESULT_FOLDER, "ENG-US_NMATSCJ-1.103-0330-page12cropped.jpg").getAbsolutePath(), 300);
        pdDocument.close();
    }
}
 
Example 27
Project: Lernkartei_2017   File: Printer.java   Source Code and License 6 votes vote down vote up
static void createPage(PDDocument temp,int count)
{
	for(int i = 0; i < count;i++)
	{
		PDPage page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
		temp.addPage(page);
	}
}
 
Example 28
Project: pdfjumbler   File: PdfEditor.java   Source Code and License 6 votes vote down vote up
@Override
public void saveDocument(List<Page> pages, File file) throws IOException {
	if (pages.size() == 0) {
		throw new IOException("Empty document.");
	}
	
	PDDocument outDoc = new PDDocument();
	
	Map<File,PDDocument> docs = new HashMap<File,PDDocument>();
	try {
		for (Page page : pages) {
			PDDocument pageDoc = docs.get(page.getFile());
			if (pageDoc == null) {
				pageDoc = PDDocument.load(page.getFile());
				docs.put(page.getFile(), pageDoc);
			}
			
			outDoc.addPage((PDPage)pageDoc.getPrintable(page.getIndex()));
		}
		
		try {
			outDoc.save(file.toString());
		}
		catch (COSVisitorException e) {
			throw new IOException(e);
		}
	}
	finally {
		outDoc.close();
		for (PDDocument doc : docs.values()) {
			doc.close();
		}
	}
}
 
Example 29
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 30
Project: pdfbox   File: App.java   Source Code and License 6 votes vote down vote up
public static void extractAttachments(String pdfPath, String extractPath) throws IOException {

  PDDocument document = null;

  try {

    File input = new File(pdfPath);

    String filePath = input.getParent() + System.getProperty("file.separator");

    document = PDDocument.load(input);

    PDDocumentNameDictionary namesDictionary =
    new PDDocumentNameDictionary( document.getDocumentCatalog() );
    PDEmbeddedFilesNameTreeNode efTree = namesDictionary.getEmbeddedFiles();

    if (efTree != null) {

      Map<String, PDComplexFileSpecification> names = efTree.getNames();

      if (names != null) {
        extractFiles(names, filePath);
      } else {

        List<PDNameTreeNode<PDComplexFileSpecification>> kids = efTree.getKids();
        for (PDNameTreeNode<PDComplexFileSpecification> node : kids) {
          names = node.getNames();
          extractFiles(names, filePath);
        };

      };

    };

    for (PDPage page : document.getPages()) {
      for (PDAnnotation annotation : page.getAnnotations()) {
        if (annotation instanceof PDAnnotationFileAttachment) {
          PDAnnotationFileAttachment annotationFileAttachment = (PDAnnotationFileAttachment) annotation;
          PDComplexFileSpecification fileSpec = (PDComplexFileSpecification) annotationFileAttachment.getFile();
          PDEmbeddedFile embeddedFile = getEmbeddedFile(fileSpec);
          extractFile(filePath, fileSpec.getFilename(), embeddedFile);
        };
      };
    };

  } finally {

  };

}
 
Example 31
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 32
Project: 484_P7_1-Java   File: ObjectExtractorStreamEngine.java   Source Code and License 6 votes vote down vote up
protected ObjectExtractorStreamEngine(PDPage page) {
    super(page);

    this.log = LoggerFactory.getLogger(ObjectExtractorStreamEngine.class);

    this.rulings = new ArrayList<>();
    this.pageTransform = null;

    // calculate page transform
    PDRectangle cb = this.getPage().getCropBox();
    int rotation = this.getPage().getRotation();

    this.pageTransform = new AffineTransform();

    if (Math.abs(rotation) == 90 || Math.abs(rotation) == 270) {
        this.pageTransform = AffineTransform.getRotateInstance(rotation * (Math.PI / 180.0), 0, 0);
        this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
    } else {
        this.pageTransform.concatenate(AffineTransform.getTranslateInstance(0, cb.getHeight()));
        this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
    }

    this.pageTransform.translate(-cb.getLowerLeftX(), -cb.getLowerLeftY());
}
 
Example 33
Project: 484_P7_1-Java   File: ObjectExtractor.java   Source Code and License 6 votes vote down vote up
protected Page extractPage(Integer pageNumber) throws IOException {

        if (pageNumber > this.pdfDocument.getNumberOfPages() || pageNumber < 1) {
            throw new java.lang.IndexOutOfBoundsException(
                    "Page number does not exist");
        }

        PDPage p = this.pdfDocument.getPage(pageNumber - 1);

        ObjectExtractorStreamEngine se = new ObjectExtractorStreamEngine(p);
        se.processPage(p);


        TextStripper pdfTextStripper = new TextStripper(this.pdfDocument, pageNumber);

        pdfTextStripper.process();

        Utils.sort(pdfTextStripper.textElements, Rectangle.ILL_DEFINED_ORDER);

        float w, h;
        int pageRotation = p.getRotation();
        if (Math.abs(pageRotation) == 90 || Math.abs(pageRotation) == 270) {
            w = p.getCropBox().getHeight();
            h = p.getCropBox().getWidth();
        } else {
            w = p.getCropBox().getWidth();
            h = p.getCropBox().getHeight();
        }

        return new Page(0, 0, w, h, pageRotation, pageNumber, p, pdfTextStripper.textElements,
                se.rulings, pdfTextStripper.minCharWidth, pdfTextStripper.minCharHeight, pdfTextStripper.spatialIndex);
    }
 
Example 34
Project: ctsms   File: Settings.java   Source Code and License 6 votes vote down vote up
private static String checkPDFTemplateFileName(String PDFTemplateFileName, String path) throws IOException, IllegalArgumentException {
	String template;
	if (PDFTemplateFileName != null && PDFTemplateFileName.length() > 0) {
		File file = new File(PDFTemplateFileName);
		if (file.exists()) {
			if (file.isFile()) {
				if (file.canRead()) {
					PDDocument doc = null;
					try {
						doc = PDDocument.load(file);
						PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);
						PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
						contentStream.close();
						template = file.getCanonicalPath();
					} catch (Exception e) {
						throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_INVALID_PDF_ERROR,
								DefaultMessages.PDF_TEMPLATE_FILE_INVALID_PDF_ERROR, PDFTemplateFileName), e);
					} finally {
						if (doc != null) {
							doc.close();
						}
					}
				} else {
					throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_ACCESS_ERROR, DefaultMessages.PDF_TEMPLATE_FILE_ACCESS_ERROR,
							PDFTemplateFileName));
				}
			} else {
				throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_NOTAFILE_ERROR, DefaultMessages.PDF_TEMPLATE_FILE_NOTAFILE_ERROR,
						PDFTemplateFileName));
			}
		} else {
			throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_DOES_NOT_EXIST_ERROR, DefaultMessages.PDF_TEMPLATE_FILE_DOES_NOT_EXIST_ERROR,
					PDFTemplateFileName));
		}
	} else {
		template = "";
	}
	return template;
}
 
Example 35
Project: ctsms   File: ProbandLetterPDFPainter.java   Source Code and License 6 votes vote down vote up
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	PDFUtil.renderTextLine(
			contentStream,
			fontA,
			PDFUtil.FontSize.TINY,
			Settings.getColor(ProbandLetterPDFSettingCodes.TEXT_COLOR, Bundle.PROBAND_LETTER_PDF, ProbandLetterPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getProbandLetterPDFLabel(Locales.PROBAND_LETTER_PDF, ProbandLetterPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(ProbandLetterPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.PROBAND_LETTER_PDF, ProbandLetterPDFDefaultSettings.PAGE_LEFT_MARGIN)
			+ (pageWidth
					- Settings.getFloat(ProbandLetterPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.PROBAND_LETTER_PDF, ProbandLetterPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings
					.getFloat(ProbandLetterPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.PROBAND_LETTER_PDF, ProbandLetterPDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f,
					Settings.getFloat(ProbandLetterPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.PROBAND_LETTER_PDF, ProbandLetterPDFDefaultSettings.PAGE_LOWER_MARGIN),
					PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example 36
Project: ctsms   File: CVPDFPainter.java   Source Code and License 6 votes vote down vote up
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	// PDFUtil.renderTextLine(
	// contentStream,
	// fontA,
	// PDFUtil.FontSize.TINY,
	// Settings.getColor(CVPDFSettingCodes.TEXT_COLOR, Bundle.CV_PDF, CVPDFDefaultSettings.TEXT_COLOR),
	// L10nUtil.getCVPDFLabel(Locales.CV_PDF, CVPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
	// Settings.getFloat(CVPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_LEFT_MARGIN)
	// + (pageWidth - Settings.getFloat(CVPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings.getFloat(
	// CVPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f,
	// Settings.getFloat(CVPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_LOWER_MARGIN), PDFUtil.Alignment.BOTTOM_CENTER);

	PDFUtil.renderTextLine(
			contentStream,
			fontA,
			PDFUtil.FontSize.TINY,
			Settings.getColor(CVPDFSettingCodes.TEXT_COLOR, Bundle.CV_PDF, CVPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getCVPDFLabel(Locales.CV_PDF, CVPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(CVPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_LEFT_MARGIN)
					+ (pageWidth - Settings.getFloat(CVPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings.getFloat(
							CVPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_RIGHT_MARGIN)),
					Settings.getFloat(CVPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.CV_PDF, CVPDFDefaultSettings.PAGE_LOWER_MARGIN), PDFUtil.Alignment.BOTTOM_RIGHT);
	writer.closeContentStream();
}
 
Example 37
Project: ctsms   File: CourseCertificatePDFPainter.java   Source Code and License 6 votes vote down vote up
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	PDFUtil.renderTextLine(
			contentStream,
			fontA,
			PDFUtil.FontSize.TINY,
			Settings.getColor(CourseCertificatePDFSettingCodes.TEXT_COLOR, Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getCourseCertificatePDFLabel(Locales.COURSE_CERTIFICATE_PDF, CourseCertificatePDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.PAGE_LEFT_MARGIN)
			+ (pageWidth
					- Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.COURSE_CERTIFICATE_PDF,
							CourseCertificatePDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_RIGHT_MARGIN,
									Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f,
									Settings.getFloat(CourseCertificatePDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.COURSE_CERTIFICATE_PDF, CourseCertificatePDFDefaultSettings.PAGE_LOWER_MARGIN),
									PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example 38
Project: ctsms   File: ReimbursementsPDFPainter.java   Source Code and License 6 votes vote down vote up
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	PDFUtil.renderTextLine(
			contentStream,
			fontD,
			PDFUtil.FontSize.TINY,
			Settings.getColor(ReimbursementsPDFSettingCodes.TEXT_COLOR, Bundle.REIMBURSEMENTS_PDF, ReimbursementsPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getReimbursementsPDFLabel(Locales.REIMBURSEMENTS_PDF, ReimbursementsPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(ReimbursementsPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.REIMBURSEMENTS_PDF, ReimbursementsPDFDefaultSettings.PAGE_LEFT_MARGIN)
			+ (pageWidth
					- Settings.getFloat(ReimbursementsPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.REIMBURSEMENTS_PDF, ReimbursementsPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings
					.getFloat(ReimbursementsPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.REIMBURSEMENTS_PDF, ReimbursementsPDFDefaultSettings.PAGE_RIGHT_MARGIN))
					/ 2.0f,
					Settings.getFloat(ReimbursementsPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.REIMBURSEMENTS_PDF, ReimbursementsPDFDefaultSettings.PAGE_LOWER_MARGIN),
					PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example 39
Project: ctsms   File: ProbandListEntryTagsPDFPainter.java   Source Code and License 6 votes vote down vote up
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	PDFUtil.renderTextLine(
			contentStream,
			fontA,
			PDFUtil.FontSize.TINY,
			Settings.getColor(ProbandListEntryTagsPDFSettingCodes.TEXT_COLOR, Bundle.PROBAND_LIST_ENTRY_TAGS_PDF, ProbandListEntryTagsPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getProbandListEntryTagsPDFLabel(Locales.PROBAND_LIST_ENTRY_TAGS_PDF, EcrfPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(ProbandListEntryTagsPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.PROBAND_LIST_ENTRY_TAGS_PDF, ProbandListEntryTagsPDFDefaultSettings.PAGE_LEFT_MARGIN)
			+ (pageWidth
					- Settings.getFloat(ProbandListEntryTagsPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.PROBAND_LIST_ENTRY_TAGS_PDF,
							ProbandListEntryTagsPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings
							.getFloat(
									ProbandListEntryTagsPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.PROBAND_LIST_ENTRY_TAGS_PDF,
									ProbandListEntryTagsPDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f,
									Settings.getFloat(ProbandListEntryTagsPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.PROBAND_LIST_ENTRY_TAGS_PDF,
											ProbandListEntryTagsPDFDefaultSettings.PAGE_LOWER_MARGIN), PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example 40
Project: ctsms   File: InquiriesPDFPainter.java   Source Code and License 6 votes vote down vote up
@Override
protected void drawPageNumber(PDFImprinter writer, PDPage page, int pageNumber, int totalPages) throws IOException {
	PDPageContentStream contentStream = writer.openContentStream(page);
	PDFUtil.renderTextLine(
			contentStream,
			fontA,
			PDFUtil.FontSize.TINY,
			Settings.getColor(InquiriesPDFSettingCodes.TEXT_COLOR, Bundle.INQUIRIES_PDF, InquiriesPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getInquiriesPDFLabel(Locales.INQUIRIES_PDF, EcrfPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(InquiriesPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.INQUIRIES_PDF, InquiriesPDFDefaultSettings.PAGE_LEFT_MARGIN)
			+ (pageWidth - Settings.getFloat(InquiriesPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.INQUIRIES_PDF, InquiriesPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings
					.getFloat(
							InquiriesPDFSettingCodes.PAGE_RIGHT_MARGIN, Bundle.INQUIRIES_PDF, InquiriesPDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f,
							Settings.getFloat(InquiriesPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.INQUIRIES_PDF, InquiriesPDFDefaultSettings.PAGE_LOWER_MARGIN), PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}