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 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 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: 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 5
Project: testarea-pdfbox2   File: RenderType3Character.java   Source Code and License 9 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 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: ctsms   File: PDFImprinter.java   Source Code and License 8 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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
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 38
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 39
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();
}
 
Example 40
Project: ctsms   File: CourseParticipantListPDFPainter.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(CourseParticipantListPDFSettingCodes.TEXT_COLOR, Bundle.COURSE_PARTICIPANT_LIST_PDF, CourseParticipantListPDFDefaultSettings.TEXT_COLOR),
			L10nUtil.getCourseParticipantListPDFLabel(Locales.COURSE_PARTICIPANT_LIST_PDF, CourseParticipantListPDFLabelCodes.PAGE_NUMBER, "", pageNumber, totalPages),
			Settings.getFloat(CourseParticipantListPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.COURSE_PARTICIPANT_LIST_PDF,
					CourseParticipantListPDFDefaultSettings.PAGE_LEFT_MARGIN)
					+ (pageWidth
							- Settings.getFloat(CourseParticipantListPDFSettingCodes.PAGE_LEFT_MARGIN, Bundle.COURSE_PARTICIPANT_LIST_PDF,
									CourseParticipantListPDFDefaultSettings.PAGE_LEFT_MARGIN) - Settings.getFloat(CourseParticipantListPDFSettingCodes.PAGE_RIGHT_MARGIN,
											Bundle.COURSE_PARTICIPANT_LIST_PDF, CourseParticipantListPDFDefaultSettings.PAGE_RIGHT_MARGIN)) / 2.0f, Settings.getFloat(
													CourseParticipantListPDFSettingCodes.PAGE_LOWER_MARGIN, Bundle.COURSE_PARTICIPANT_LIST_PDF, CourseParticipantListPDFDefaultSettings.PAGE_LOWER_MARGIN),
													PDFUtil.Alignment.BOTTOM_CENTER);
	writer.closeContentStream();
}
 
Example 41
Project: ctsms   File: PDFPainterBase.java   Source Code and License 6 votes vote down vote up
@Override
public void drawPageNumbers(PDFImprinter writer)
		throws Exception {
	if (drawPageNumbers) {
		int i = 1;
		int j = 0;
		Iterator it = writer.getDocument().getDocumentCatalog().getAllPages().iterator();
		while (it.hasNext()) {
			int totalPages = totalPageCounts.get(j);
			drawPageNumber(writer, (PDPage) it.next(), i, totalPages);
			i++;
			if (i > totalPages) {
				j++;
				i = 1;
			}
		}
	}
}
 
Example 42
Project: gcs   File: PdfPanel.java   Source Code and License 6 votes vote down vote up
private void markPageForLoading() {
    int numberOfPages = mPdf.getNumberOfPages();
    if (mPageIndex >= 0 && mPageIndex == numberOfPages) {
        mPageIndex = numberOfPages - 1;
    }
    if (mPageIndex >= 0 && mPageIndex < numberOfPages) {
        PDPage page = mPdf.getPage(mPageIndex);
        PDRectangle cropBox = page.getCropBox();
        float scale = SCALES[mScaleIndex] * Toolkit.getDefaultToolkit().getScreenResolution();
        mWidth = (int) Math.ceil(cropBox.getWidth() / 72 * scale);
        mHeight = (int) Math.ceil(cropBox.getHeight() / 72 * scale);
        mImg = null;
        mNeedLoad = true;
        Dimension size = new Dimension(mWidth, mHeight);
        UIUtilities.setOnlySize(this, size);
        setSize(size);
        repaint();
        mIgnorePageChange = true;
        mOwner.updateStatus(mPageIndex, numberOfPages, SCALES[mScaleIndex]);
        mIgnorePageChange = false;
    }
}
 
Example 43
Project: testarea-pdfbox2   File: TestClipPathFinder.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28321374/how-to-get-page-content-height-using-pdfbox">
 * How to get page content height using pdfbox
 * </a>
 * <br/>
 * <a href="http://d.pr/f/137PF">
 * test-pdf4.pdf
 * </a>
 * <br/>
 * <a href="http://d.pr/f/15uBF">
 * test-pdf5.pdf
 * </a>
 * <p>
 * The clip paths found here correspond to the Illustrator compound elements.
 * </p>
 */
@Test
public void testTestPdf4() throws IOException
{
    try (InputStream resource = getClass().getResourceAsStream("test-pdf4.pdf"))
    {
        System.out.println("test-pdf4.pdf");
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getPage(0);
        ClipPathFinder finder = new ClipPathFinder(page);
        finder.findClipPaths();
        
        for (Path path : finder)
        {
            System.out.println(path);
        }
        
        document.close();
    }
}
 
Example 44
Project: testarea-pdfbox2   File: TestClipPathFinder.java   Source Code and License 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/28321374/how-to-get-page-content-height-using-pdfbox">
 * How to get page content height using pdfbox
 * </a>
 * <br/>
 * <a href="http://d.pr/f/137PF">
 * test-pdf4.pdf
 * </a>
 * <br/>
 * <a href="http://d.pr/f/15uBF">
 * test-pdf5.pdf
 * </a>
 * <p>
 * The clip paths found here correspond to the Illustrator compound elements.
 * </p>
 */
@Test
public void testTestPdf5() throws IOException
{
    try (InputStream resource = getClass().getResourceAsStream("test-pdf5.pdf"))
    {
        System.out.println("test-pdf5.pdf");
        PDDocument document = PDDocument.load(resource);
        PDPage page = document.getPage(0);
        ClipPathFinder finder = new ClipPathFinder(page);
        finder.findClipPaths();
        
        for (Path path : finder)
        {
            System.out.println(path);
        }
        
        document.close();
    }
}
 
Example 45
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawDepartmentBackgroundColorBack(PDPage page, Attendee attendee) throws IOException {
    PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    stream.setStrokingColor(Color.decode(attendee.getStaffDepartmentColor()));
    stream.setNonStrokingColor(Color.decode(attendee.getStaffDepartmentColor()));
    stream.addRect(45, 144, 45, 387);  // Left hand vertical
    stream.fill();
    stream.close();
}
 
Example 46
Project: kumoreg   File: StaffBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawNameBack(PDPage page, Attendee attendee) throws IOException {
    // Name bounding box:
    //         stream.fillRect(105, 152, 190, 63);

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

    ResizeOptions opts = new ResizeOptions();
    opts.centered = true;
    opts.font = bankGothic;
    opts.lines = 2;
    opts.maxTextWidth = 190;
    opts.minFontSize = 8;
    opts.size = 36;

    drawStringWithResizing(stream, 195, 190, attendee.getFirstName(), opts);
    drawStringWithResizing(stream, 195, 160, attendee.getLastName(), opts);
    stream.close();
}
 
Example 47
Project: kumoreg   File: LiteBadgePrintFormatter.java   Source Code and License 6 votes vote down vote up
/**
 * Generates a PDF containing badges ready to be printed. Lite badges have no Fan Name or number.
 * @param attendees Attendees to generate badges for
 * @param xOffset Horizontal offset in points (1/72 inch)
 * @param yOffset Vertical offset in points (1/72 inch)
 */
public LiteBadgePrintFormatter(List<Attendee> attendees, Integer xOffset, Integer yOffset) {
    PDDocument document;
    this.xOffset = (xOffset == null) ? 0 : xOffset;
    this.yOffset = (yOffset == null) ? 0 : yOffset;

    try {
        document = new PDDocument();
        for (Attendee attendee : attendees) {
            PDPage currentPage = generatePage(attendee, document);
            document.addPage( currentPage );
        }

        document.save(os);
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 48
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
void addBadge(Attendee attendee, Integer xOffset, Integer yOffset) throws IOException {
//        PDPage templatePage = frontBackground.getDocumentCatalog().getPages().get(0);
//        COSDictionary pageDict = templatePage.getCOSObject();
//        COSDictionary newPageDict = new COSDictionary(pageDict);
//        newPageDict.removeItem(COSName.ANNOTS);
//        newPageDict.removeItem(COSName.ACTUAL_TEXT);
//
//        PDPage page = document.importPage(new PDPage(newPageDict));
        this.xOffset = xOffset; // Todo: don't store this in the class
        this.yOffset = yOffset;
        PDPage page = document.importPage(new PDPage(new PDRectangle(612f, 396f)));

        // Positions are measured from the bottom left corner of the page at 72 DPI
        drawAgeColorStripe(page, attendee);
        drawVerticalAgeRangeText(page, bankGothic, attendee);
        drawName(page, attendee);
        drawBadgeTypeStripe(page, attendee);
        drawBadgeTypeText(page, bankGothic, attendee);
        drawBadgeNumber(page, bankGothic, attendee);
    }
 
Example 49
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawBadgeTypeText(PDPage page, PDFont font, Attendee attendee) throws IOException {
        if (attendee.getBadge() == null || attendee.getBadge().getBadgeTypeText() == null) {
            return;     // no text, don't draw anything
        }
        String badgeTypeText = attendee.getBadge().getBadgeTypeText();
        PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);

//        PDRectangle boundingBox = new PDRectangle(206, 85, 253, 44);

        stream.setLineWidth(0.5f);
        stream.beginText();
        int fontSize = BadgeLib.findMaxLineSize(font, badgeTypeText,240, 40);
        stream.setFont(font, fontSize);
        if (attendee.getBadge() != null &&
                (attendee.getBadge().getBadgeTypeText().equals("Friday") ||
                        attendee.getBadge().getBadgeTypeText().equals("Saturday") ||
                        attendee.getBadge().getBadgeTypeText().equals("Sunday"))) {
            if (attendee.getBadge() != null && attendee.getBadge().getBadgeTypeBackgroundColor() != null) {
                stream.setNonStrokingColor(BadgeLib.getForegroundColor(attendee.getCurrentAgeRange().getStripeColor()));
            } else {
                stream.setNonStrokingColor(Color.WHITE);
                stream.setStrokingColor(Color.black);
            }

        } else {
            if (attendee.getBadge() != null && attendee.getBadge().getBadgeTypeBackgroundColor() != null) {
                stream.setNonStrokingColor(BadgeLib.getForegroundColor(attendee.getBadge().getBadgeTypeBackgroundColor()));
            } else {
                stream.setNonStrokingColor(Color.WHITE);
                stream.setStrokingColor(Color.black);
            }

        }

        float textWidth = font.getStringWidth(badgeTypeText);
        Float offset = textWidth * (fontSize/(2*1000.0f));
        stream.newLineAtOffset(330-offset, 100);   // First character position
        stream.showText(badgeTypeText);
        stream.close();
    }
 
Example 50
Project: kumoreg   File: AttendeeBadge2017.java   Source Code and License 6 votes vote down vote up
private void drawAgeColorStripe(PDPage page, Attendee attendee) throws IOException {
    PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    // This only needs to be set once in the page to set the global offset.
    stream.concatenate2CTM(1, 0, 0, 1, xOffset, yOffset);

    if (attendee.getCurrentAgeRange() != null) {
        stream.setNonStrokingColor(Color.decode(attendee.getCurrentAgeRange().getStripeColor()));
    } else {
        stream.setNonStrokingColor(Color.black);
    }
    stream.addRect(160, 85, 46, 230);
    stream.fill();
    stream.close();
}
 
Example 51
Project: testarea-pdfbox2   File: RotatePageContent.java   Source Code and License 6 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 and then set the crop
 * box and media box to the bounding rectangle of the rotated page area.
 * </p>
 */
@Test
public void testRotateExpandBox() 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);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        PDRectangle newBox = new PDRectangle((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight());
        page.setCropBox(newBox);
        page.setMediaBox(newBox);

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-expand-box.pdf"));
    }
}
 
Example 52
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public PDPage generatePage(String typeOfPdf, PDDocument generatedPdDocument) {
    PDPage page = new PDPage();
    page.setMediaBox(getConfiguredPdfPageSize(typeOfPdf));
    generatedPdDocument.addPage(page);
    return page;
}
 
Example 53
Project: pcm-api   File: PdfBoxServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void addColorBox(Color color, float xCoordinate, float yCoordinate, float width, float height, PDPage page, PDPageContentStream contents) throws IOException {
    contents.setNonStrokingColor(color);
    contents.addRect(page.getMediaBox().getLowerLeftX() + xCoordinate, page.getMediaBox().getLowerLeftY() + yCoordinate, width, height);
    contents.fill();

    // Reset changed color
    resetChangedColorToDefault(contents);
}
 
Example 54
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 55
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addAuthorizationToDisclose(Consent consent, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    final float cardXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    final float colAWidth = 180f;
    final float colBWidth = 90f;
    final float colCWidth = 200f;
    final float colDWidth = 90f;
    String title = getI18nMessage("CONSENT.PDF.SECTION1.TITLE");
    drawSectionHeader(title, cardXCoordinate, startYCoordinate, page, contentStream);

    List<Column> tableColumns = Arrays.asList(new Column(colAWidth), new Column(colBWidth), new Column(colCWidth), new Column(colDWidth));

    // Provider permitted to disclose
    float providerPermittedStartYCoordinate = startYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    addProviderPermittedToDisclose(consent, tableColumns, providerPermittedStartYCoordinate, font, page, contentStream);

    // Provider disclosure is made to
    float providerDisclosureIsMadeToStartYCoordinate = 485f;
    addProviderDisclosureIsMadeTo(consent, tableColumns, providerDisclosureIsMadeToStartYCoordinate, font, page, contentStream);
}
 
Example 56
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addProviderPermittedToDisclose(Consent consent, List<Column> tableColumns, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    String label = getI18nMessage("CONSENT.PDF.SECTION1.CONTENT1");
    addAuthorizationTableHeader(label, startYCoordinate, tableColumns, font, contentStream);

    // From providers details
    final float fromProviderDetailsYCoordinate = 257f;
    Set<OrganizationalProvider> fromOrganizations = consent.getOrganizationalProvidersPermittedToDisclose().stream()
            .map(ConsentOrganizationalProviderPermittedToDisclose::getOrganizationalProvider)
            .collect(Collectors.toSet());

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

    addConsentProvidersDetails(fromOrganizations, fromPractitioners, tableColumns, fromProviderDetailsYCoordinate, page, contentStream);
}
 
Example 57
Project: pcm-api   File: ConsentPdfGeneratorImpl.java   Source Code and License 6 votes vote down vote up
private void addConsentTerms(String consentTerms, Patient patient, float startYCoordinate, PDFont font, PDPage page, PDPageContentStream contentStream) throws IOException {
    float cardXCoordinate = PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER;
    final float paragraphYCoordinate = startYCoordinate - PdfBoxStyle.XLARGE_LINE_SPACE;
    final String title = getI18nMessage("CONSENT.PDF.SECTION3.TITLE");

    drawSectionHeader(title, cardXCoordinate, startYCoordinate, page, contentStream);

    final String userNameKey = "ATTESTER_FULL_NAME";
    String termsWithAttestedName = consentTerms.replace(userNameKey, patient.getFirstName().concat(SPACE_PATTERN + patient.getLastName()));

    try {
        pdfBoxService.addWrappedParagraphByLineBreaks(termsWithAttestedName, font, PdfBoxStyle.TEXT_SMALL_SIZE, Color.BLACK, paragraphYCoordinate, PdfBoxStyle.LEFT_RIGHT_MARGINS_OF_LETTER, page, contentStream);
    } catch (Exception e) {
        log.error("Invalid character for cast specification", e);
        throw new InvalidContentException(e);
    }
}
 
Example 58
Project: cat-boot   File: ReportLink.java   Source Code and License 6 votes vote down vote up
private float addLink(PDDocument document, int pageNumber, float startX, float startY, PdfTextStyle textConfig) {
    PDAnnotationLink txtLink = new PDAnnotationLink();
    txtLink.setColor(textConfig.getColor());

    PDBorderStyleDictionary underline = getLinkUnderline();
    txtLink.setBorderStyle(underline);

    try {
        float textWidth = (textConfig.getFont().getStyle(textConfig.getStyle()).getStringWidth(text) / 1000) * textConfig.getFontSize();

        float startLinkY = startY + textConfig.getFontSize();
        float endLinkY = startY - underline.getWidth();

        PDRectangle position = new PDRectangle();
        position.setLowerLeftX(startX);
        position.setLowerLeftY(startLinkY);
        position.setUpperRightX(startX + textWidth);
        position.setUpperRightY(endLinkY);
        txtLink.setRectangle(position);

        PDActionURI action = new PDActionURI();
        action.setURI(link);
        txtLink.setAction(action);

        PDPage page = document.getDocumentCatalog().getPages().get(pageNumber);
        page.getAnnotations().add(txtLink);

        return endLinkY;
    } catch (IOException e) {
        LOG.warn("Could not add link: " + e.getClass() + " - " + e.getMessage());
        return startY;
    }
}
 
Example 59
Project: cat-boot   File: PdfReportGenerator.java   Source Code and License 6 votes vote down vote up
private void breakPage(PDDocument document, PrintCursor cursor, PrintData printData) throws IOException {
    if (cursor.currentStream != null) {
        cursor.currentStream.close();
    }

    if (printData.templateResource == null) {
        document.addPage(new PDPage(printData.pageConfig.getPageSize()));
    } else {
        PDDocument templateDoc = PDDocument.load(printData.templateResource.getInputStream());
        cursor.cacheTempalte(templateDoc);
        PDPage templatePage = templateDoc.getDocumentCatalog().getPages().get(0);
        document.importPage(templatePage);
    }
    PDPage currPage = document.getDocumentCatalog().getPages().get(++cursor.currentPageNumber);
    cursor.currentStream = new PDPageContentStream(document, currPage, PDPageContentStream.AppendMode.APPEND, false);
    cursor.yPos = printData.pageConfig.getStartY(cursor.currentPageNumber);
    cursor.xPos = printData.pageConfig.getStartX();
}
 
Example 60
Project: memoria-politica   File: FedDepPhotosUtility.java   Source Code and License 6 votes vote down vote up
private static void buildImgKeyToPolNameMapping(PDPage page) throws IOException {
    PDStream contents = page.getContents();
    PDFStreamParser parser = new PDFStreamParser(contents.getStream());
    parser.parse();
    List tokens = parser.getTokens();

    boolean concatStringPhase = false;
    String polName = "";
    String lastText = "";

    for (int index = 0; index < tokens.size(); index++) {
        Object obj = tokens.get(index);

        if (obj instanceof PDFOperator) {
            PDFOperator op = (PDFOperator) obj;
            if (op.getOperation().equals("BT")) {
                concatStringPhase = true;
                polName = lastText;
                lastText = "";
            }
            else if (op.getOperation().equals("ET")) {
                concatStringPhase = false;
            }
        }
        else if (concatStringPhase && obj instanceof COSString) {
            COSString cosString = (COSString) obj;
            lastText += " " + cosString.getString();
            lastText = lastText.trim();
        }
        else if (!concatStringPhase && obj instanceof COSName) {
            COSName cosName = (COSName) obj;
            if (cosName.getName().startsWith("img")) {
                mapImgKeyToPolName.put(cosName.getName(), polName);
            }
        }
    }
}