java.awt.print.PrinterIOException#org.apache.pdfbox.pdmodel.common.PDRectangle源码实例Demo

下面列出了java.awt.print.PrinterIOException#org.apache.pdfbox.pdmodel.common.PDRectangle 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Knowage-Server   文件: PDFCreator.java
private static void writeFrontpageDetails(PDDocument doc, PDFont font, float fontSize, FrontpageDetails details) throws IOException {
	String name = "Name: " + details.getName();
	String description = "Description: " + details.getDescription();
	String date = "Date: " + DEFAULT_DATE_FORMATTER.format(details.getDate());
	PDPage page = doc.getPage(0);
	PDRectangle pageSize = page.getMediaBox();
	float stringWidth = font.getStringWidth(StringUtilities.findLongest(name, description, date)) * fontSize / 1000f;
	float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

	int rotation = page.getRotation();
	boolean rotate = rotation == 90 || rotation == 270;
	float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
	float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
	float startX = rotate ? pageHeight / 3f : (pageWidth - stringWidth - stringHeight) / 3f;
	float startY = rotate ? (pageWidth - stringWidth) / 1f : pageWidth / 0.9f;

	// append the content to the existing stream
	try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {
		// draw rectangle
		writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, name, description, date);
	}
}
 
源代码2 项目: Open-Lowcode   文件: PDFPage.java
@Override
protected void print(PDDocument document) throws IOException {
	// create the page
	this.document = document;
	page = new PDPage(new PDRectangle(width * MM_TO_POINT, height * MM_TO_POINT));
	document.addPage(page);
	contentStream = new PDPageContentStream(document, page);
	// print the widgets
	for (int i = 0; i < widgetstoprint.size(); i++) {
		PageExecutable thiswidget = widgetstoprint.get(i);
		thiswidget.printComponent();
	}
	// close the page
	contentStream.close();

}
 
源代码3 项目: tabula-java   文件: ObjectExtractorStreamEngine.java
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());
}
 
源代码4 项目: testarea-pdfbox2   文件: RotatePageContent.java
/**
 * <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 move its crop box and
 * media box accordingly to make it appear as if the content was rotated around
 * the center of the crop box.
 * </p>
 */
@Test
public void testRotateMoveBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(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();
        float cx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float cy = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        Point2D.Float newC = matrix.transformPoint(cx, cy);
        float tx = (float)newC.getX() - cx;
        float ty = (float)newC.getY() - cy;
        page.setCropBox(new PDRectangle(cropBox.getLowerLeftX() + tx, cropBox.getLowerLeftY() + ty, cropBox.getWidth(), cropBox.getHeight()));
        PDRectangle mediaBox = page.getMediaBox();
        page.setMediaBox(new PDRectangle(mediaBox.getLowerLeftX() + tx, mediaBox.getLowerLeftY() + ty, mediaBox.getWidth(), mediaBox.getHeight()));

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-move-box.pdf"));
    }
}
 
源代码5 项目: gcs   文件: PDCIDFontType0.java
private BoundingBox generateBoundingBox()
{
    if (getFontDescriptor() != null) {
        PDRectangle bbox = getFontDescriptor().getFontBoundingBox();
        if (bbox.getLowerLeftX() != 0 || bbox.getLowerLeftY() != 0 ||
            bbox.getUpperRightX() != 0 || bbox.getUpperRightY() != 0) {
            return new BoundingBox(bbox.getLowerLeftX(), bbox.getLowerLeftY(),
                                   bbox.getUpperRightX(), bbox.getUpperRightY());
        }
    }
    if (cidFont != null)
    {
        return cidFont.getFontBBox();
    }
    else
    {
        try
        {
            return t1Font.getFontBBox();
        }
        catch (IOException e)
        {
            return new BoundingBox();
        }
    }
}
 
源代码6 项目: Knowage-Server   文件: PDFCreator.java
private static void createPDF(List<InputStream> inputImages, Path output) throws IOException {
	PDDocument document = new PDDocument();
	try {
		for (InputStream is : inputImages) {
			BufferedImage bimg = ImageIO.read(is);
			float width = bimg.getWidth();
			float height = bimg.getHeight();
			PDPage page = new PDPage(new PDRectangle(width, height));
			document.addPage(page);

			PDImageXObject img = LosslessFactory.createFromImage(document, bimg);
			try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
				contentStream.drawImage(img, 0, 0);
			}
		}
		document.save(output.toFile());
	} finally {
		document.close();
	}
}
 
源代码7 项目: ctsms   文件: PDFImprinter.java
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;
}
 
源代码8 项目: gcs   文件: AppearanceGeneratorHelper.java
private AffineTransform calculateMatrix(PDRectangle bbox, int rotation)
{
    if (rotation == 0)
    {
        return new AffineTransform();
    }
    float tx = 0, ty = 0;
    switch (rotation)
    {
        case 90:
            tx = bbox.getUpperRightY();
            break;
        case 180:
            tx = bbox.getUpperRightY();
            ty = bbox.getUpperRightX();
            break;
        case 270:
            ty = bbox.getUpperRightX();
            break;
        default:
            break;
    }
    Matrix matrix = Matrix.getRotateInstance(Math.toRadians(rotation), tx, ty);
    return matrix.createAffineTransform();

}
 
源代码9 项目: dss   文件: SignatureImageAndPositionProcessor.java
private static float processY(int rotation, ImageAndResolution ires, BufferedImage visualImageSignature, PDPage pdPage, SignatureImageParameters signatureImageParameters) {
    float y;
    
    PDRectangle pageBox = pdPage.getMediaBox();
    float height = getHeight(signatureImageParameters, visualImageSignature, ires, ImageRotationUtils.isSwapOfDimensionsRequired(rotation));
    
    switch (rotation) {
        case ImageRotationUtils.ANGLE_90:
            y = processYAngle90(pageBox, signatureImageParameters, height);
            break;
        case ImageRotationUtils.ANGLE_180:
            y = processYAngle180(pageBox, signatureImageParameters, height);
            break;
        case ImageRotationUtils.ANGLE_270:
            y = processYAngle270(pageBox, signatureImageParameters, height);
            break;
        case ImageRotationUtils.ANGLE_360:
            y = processYAngle360(pageBox, signatureImageParameters, height);
            break;
        default:
            throw new IllegalStateException(ImageRotationUtils.SUPPORTED_ANGLES_ERROR_MESSAGE);
    }

    return y;
}
 
@SuppressWarnings("unchecked")
public List<BufferedImage> toImages(PDDocument pdDocument, int startPage, int endPage, int resolution, int imageType) throws Exception {
    final List<BufferedImage> result = new ArrayList<BufferedImage>();
    final List<PDPage> pages = pdDocument.getDocumentCatalog().getAllPages();
    final int pagesSize = pages.size();

    for (int i = startPage - 1; i < endPage && i < pagesSize; i++) {
        PDPage page = pages.get(i);
        PDRectangle cropBox = page.findCropBox();
        float width = cropBox.getWidth();
        float height = cropBox.getHeight();
        int currResolution = calculateResolution(resolution, width, height);
        BufferedImage image = page.convertToImage(imageType, currResolution);

        if (image != null) {
            result.add(image);
        }
    }

    return result;
}
 
源代码11 项目: gcs   文件: PDTextAppearanceHandler.java
private void drawCrossHairs(PDAnnotationText annotation, final PDAppearanceContentStream contentStream)
        throws IOException
{
    PDRectangle bbox = adjustRectAndBBox(annotation, 20, 20);

    float min = Math.min(bbox.getWidth(), bbox.getHeight());

    contentStream.setMiterLimit(4);
    contentStream.setLineJoinStyle(0);
    contentStream.setLineCapStyle(0);
    contentStream.setLineWidth(0.61f); // value from Adobe

    contentStream.transform(Matrix.getScaleInstance(0.001f * min / 1.5f, 0.001f * min / 1.5f));
    contentStream.transform(Matrix.getTranslateInstance(0, 50));

    // we get the shape of a Symbol crosshair (0x2295) and use that one.
    // Adobe uses a different font (which one?), or created the shape from scratch.
    GeneralPath path = PDType1Font.SYMBOL.getPath("circleplus");
    addPath(contentStream, path);
    contentStream.fillAndStroke();
}
 
源代码12 项目: gcs   文件: PDTextAppearanceHandler.java
private void drawCheck(PDAnnotationText annotation, final PDAppearanceContentStream contentStream)
        throws IOException
{
    PDRectangle bbox = adjustRectAndBBox(annotation, 20, 19);

    float min = Math.min(bbox.getWidth(), bbox.getHeight());

    contentStream.setMiterLimit(4);
    contentStream.setLineJoinStyle(1);
    contentStream.setLineCapStyle(0);
    contentStream.setLineWidth(0.59f); // value from Adobe

    contentStream.transform(Matrix.getScaleInstance(0.001f * min / 0.8f, 0.001f * min / 0.8f));
    contentStream.transform(Matrix.getTranslateInstance(0, 50));

    // we get the shape of a Zapf Dingbats check (0x2714) and use that one.
    // Adobe uses a different font (which one?), or created the shape from scratch.
    GeneralPath path = PDType1Font.ZAPF_DINGBATS.getPath("a20");
    addPath(contentStream, path);
    contentStream.fillAndStroke();
}
 
源代码13 项目: testarea-pdfbox2   文件: RotatePageContent.java
/**
 * <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 = Loader.loadPDF(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"));
    }
}
 
源代码14 项目: gcs   文件: FDFAnnotationCircle.java
private void initFringe(Element element) throws IOException
{
    String fringe = element.getAttribute("fringe");
    if (fringe != null && !fringe.isEmpty())
    {
        String[] fringeValues = fringe.split(",");
        if (fringeValues.length != 4)
        {
            throw new IOException("Error: wrong amount of numbers in attribute 'fringe'");
        }
        PDRectangle rect = new PDRectangle();
        rect.setLowerLeftX(Float.parseFloat(fringeValues[0]));
        rect.setLowerLeftY(Float.parseFloat(fringeValues[1]));
        rect.setUpperRightX(Float.parseFloat(fringeValues[2]));
        rect.setUpperRightY(Float.parseFloat(fringeValues[3]));
        setFringe(rect);
    }
}
 
源代码15 项目: gcs   文件: PDCIDFontType2.java
private BoundingBox generateBoundingBox() throws IOException
{
    if (getFontDescriptor() != null)
    {
        PDRectangle bbox = getFontDescriptor().getFontBoundingBox();
        if (bbox != null &&
                (Float.compare(bbox.getLowerLeftX(), 0) != 0 || 
                 Float.compare(bbox.getLowerLeftY(), 0) != 0 ||
                 Float.compare(bbox.getUpperRightX(), 0) != 0 ||
                 Float.compare(bbox.getUpperRightY(), 0) != 0))
        {
            return new BoundingBox(bbox.getLowerLeftX(), bbox.getLowerLeftY(),
                                   bbox.getUpperRightX(), bbox.getUpperRightY());
        }
    }
    return ttf.getFontBBox();
}
 
源代码16 项目: science-parse   文件: PDFExtractor.java
@Override
protected void endPage(PDPage pdfboxPage) {
  if (!curLineTokens.isEmpty()) {
    curLines.add(toLine(curLineTokens));
  }
  PDRectangle pageRect = pdfboxPage.getMediaBox() == null ?
    pdfboxPage.getArtBox() :
    pdfboxPage.getMediaBox();
  val page = PDFPage.builder()
    .lines(new ArrayList<>(curLines))
    .pageNumber(pages.size())
    .pageWidth((int) pageRect.getWidth())
    .pageHeight((int) pageRect.getHeight())
    .build();
  pages.add(page);
}
 
源代码17 项目: gcs   文件: FDFAnnotationFreeText.java
private void initFringe(Element element) throws IOException
{
    String fringe = element.getAttribute("fringe");
    if (fringe != null && !fringe.isEmpty())
    {
        String[] fringeValues = fringe.split(",");
        if (fringeValues.length != 4)
        {
            throw new IOException("Error: wrong amount of numbers in attribute 'fringe'");
        }
        PDRectangle rect = new PDRectangle();
        rect.setLowerLeftX(Float.parseFloat(fringeValues[0]));
        rect.setLowerLeftY(Float.parseFloat(fringeValues[1]));
        rect.setUpperRightX(Float.parseFloat(fringeValues[2]));
        rect.setUpperRightY(Float.parseFloat(fringeValues[3]));
        setFringe(rect);
    }
}
 
源代码18 项目: PDF4Teachers   文件: PageRenderer.java
public void updatePosition(int totalHeight){
    if(totalHeight == -1) totalHeight = (int) getTranslateY();

    PDRectangle pageSize = MainWindow.mainScreen.document.pdfPagesRender.getPageSize(page);
    final double ratio = pageSize.getHeight() / pageSize.getWidth();

    setWidth(MainWindow.mainScreen.getPageWidth());
    setHeight(MainWindow.mainScreen.getPageWidth() * ratio);

    setMaxWidth(MainWindow.mainScreen.getPageWidth());
    setMinWidth(MainWindow.mainScreen.getPageWidth());

    setMaxHeight(MainWindow.mainScreen.getPageWidth() * ratio);
    setMinHeight(MainWindow.mainScreen.getPageWidth() * ratio);

    setTranslateX(30);
    setTranslateY(totalHeight);

    totalHeight = (int) (totalHeight + getHeight() + 30);

    if(MainWindow.mainScreen.document.totalPages > page+1){
        MainWindow.mainScreen.document.pages.get(page + 1).updatePosition(totalHeight);
    }else{
        MainWindow.mainScreen.updateSize(totalHeight);
    }

    if(pageEditPane != null) pageEditPane.updatePosition();

}
 
源代码19 项目: gcs   文件: PDFontDescriptor.java
/**
 * Set the fonts bounding box.
 *
 * @param rect The new bouding box.
 */
public void setFontBoundingBox( PDRectangle rect )
{
    COSArray array = null;
    if( rect != null )
    {
        array = rect.getCOSArray();
    }
    dic.setItem( COSName.FONT_BBOX, array );
}
 
源代码20 项目: gcs   文件: LayerUtility.java
/**
 * Places the given form over the existing content of the indicated page (like an overlay).
 * The form is enveloped in a marked content section to indicate that it's part of an
 * optional content group (OCG), here used as a layer. This optional group is returned and
 * can be enabled and disabled through methods on {@link PDOptionalContentProperties}.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before calling this method to make
 * sure that the graphics state is reset.
 *
 * @param targetPage the target page
 * @param form the form to place
 * @param transform the transformation matrix that controls the placement of your form. You'll
 * need this if your page has a crop box different than the media box, or if these have negative
 * coordinates, or if you want to scale or adjust your form.
 * @param layerName the name for the layer/OCG to produce
 * @return the optional content group that was generated for the form usage
 * @throws IOException if an I/O error occurs
 */
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
        PDFormXObject form, AffineTransform transform,
        String layerName) throws IOException
{
    PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    if (ocprops.hasGroup(layerName))
    {
        throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
    }

    PDRectangle cropBox = targetPage.getCropBox();
    if ((cropBox.getLowerLeftX() < 0 || cropBox.getLowerLeftY() < 0) && transform.isIdentity())
    {
        // PDFBOX-4044 
        LOG.warn("Negative cropBox " + cropBox + 
                 " and identity transform may make your form invisible");
    }

    PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
    ocprops.addGroup(layer);

    PDPageContentStream contentStream = new PDPageContentStream(
            targetDoc, targetPage, AppendMode.APPEND, !DEBUG);
    contentStream.beginMarkedContent(COSName.OC, layer);
    contentStream.saveGraphicsState();
    contentStream.transform(new Matrix(transform));
    contentStream.drawForm(form);
    contentStream.restoreGraphicsState();
    contentStream.endMarkedContent();
    contentStream.close();

    return layer;
}
 
COSDictionary buildUnembeddedArialWithSpecialEncoding() {
    COSArray differences = new COSArray();
    differences.add(COSInteger.get(32));
    differences.add(COSName.getPDFName("uniAB55"));

    COSDictionary fontDescDict = new COSDictionary();
    fontDescDict.setName("Type", "FontDescriptor");
    fontDescDict.setName("FontName", "Arial");
    fontDescDict.setString("FontFamily", "Arial");
    fontDescDict.setInt("Flags", 32);
    fontDescDict.setItem("FontBBox", new PDRectangle(-665, -325, 2665, 1365));
    fontDescDict.setInt("ItalicAngle", 0);
    fontDescDict.setInt("Ascent", 1040);
    fontDescDict.setInt("Descent", -325);
    fontDescDict.setInt("CapHeight", 716);
    fontDescDict.setInt("StemV", 88);
    fontDescDict.setInt("XHeight", 519);

    COSDictionary encodingDict = new COSDictionary();
    encodingDict.setName("Type", "Encoding");
    encodingDict.setName("BaseEncoding", "WinAnsiEncoding");
    encodingDict.setItem("Differences", differences);

    COSArray widths = new COSArray();
    widths.add(COSInteger.get(500));

    COSDictionary fontDict = new COSDictionary();
    fontDict.setName("Type", "Font");
    fontDict.setName("Subtype", "TrueType");
    fontDict.setName("BaseFont", "Arial");
    fontDict.setInt("FirstChar", 32);
    fontDict.setInt("LastChar", 32);
    fontDict.setItem("Widths", widths);
    fontDict.setItem("FontDescriptor", fontDescDict);
    fontDict.setItem("Encoding", encodingDict);

    return fontDict;
}
 
源代码22 项目: testarea-pdfbox2   文件: AddImageSaveIncremental.java
/** @see #testAddImagesLikeUser11465050Improved() */
void addImageLikeUser11465050Improved(PDDocument document, PDImageXObject image) throws IOException {
    PDPage page = document.getPage(0);
    PDRectangle pageSize = page.getMediaBox();
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
    contentStream.drawImage(image, pageSize.getLowerLeftX(), pageSize.getLowerLeftY(), pageSize.getWidth(), pageSize.getHeight());
    contentStream.close();

    page.getCOSObject().setNeedToBeUpdated(true);
    page.getResources().getCOSObject().setNeedToBeUpdated(true);
    page.getResources().getCOSObject().getCOSDictionary(COSName.XOBJECT).setNeedToBeUpdated(true);
    document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true);
    document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true);
}
 
源代码23 项目: easytable   文件: MinimumWorkingExample.java
public static void main(String[] args) throws IOException {

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

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

                // Build the table
                Table myTable = Table.builder()
                        .addColumnsOfWidth(100, 100)
                        .addRow(Row.builder()
                                .add(TextCell.builder().text("One One").borderWidth(1).backgroundColor(Color.GRAY).build())
                                .add(TextCell.builder().text("One Two").borderWidth(1).backgroundColor(Color.LIGHT_GRAY).build())
                                .build())
                        .addRow(Row.builder()
                                .add(TextCell.builder().text("Two One").borderWidth(1).textColor(Color.RED).build())
                                .add(TextCell.builder().text("Two Two").borderWidth(1).horizontalAlignment(HorizontalAlignment.RIGHT).build())
                                .build())
                        .build();

                // Set up the drawer
                TableDrawer tableDrawer = TableDrawer.builder()
                        .contentStream(contentStream)
                        .startX(20f)
                        .startY(page.getMediaBox().getUpperRightY() - 20f)
                        .table(myTable)
                        .build();

                // And go for it!
                tableDrawer.draw();
            }

            document.save("example.pdf");
        }
    }
 
源代码24 项目: pdfbox-layout   文件: CompatibilityHelper.java
public static PDAnnotationLink createLink(PDPage page, PDRectangle rect, Color color,
    LinkStyle linkStyle, final String uri) {
PDAnnotationLink pdLink = createLink(page, rect, color, linkStyle);

PDActionURI actionUri = new PDActionURI();
actionUri.setURI(uri);
pdLink.setAction(actionUri);
return pdLink;
   }
 
/**
* 
* @param page page to parse
*/
@Override
public void processPage(PDPage page) throws IOException {
    PDRectangle pageRectangle = page.getMediaBox();
    if (pageRectangle!= null) {
        this.setCurrentPageWidth(pageRectangle.getWidth());
        super.processPage(page);
        this.previousTextPosition = null;
        this.textLineList = new ArrayList<TextLine>();
    }
}
 
源代码26 项目: easytable   文件: TableOverSeveralPagesTest.java
private void drawMultipageTableOn(PDDocument document) throws IOException {
    TableDrawer.builder()
            .table(createTable())
            .startX(50)
            .startY(100F)
            .endY(50F) // note: if not set, table is drawn over the end of the page
            .build()
            .draw(() -> document, () -> new PDPage(PDRectangle.A4), 50f);
}
 
源代码27 项目: testarea-pdfbox2   文件: AddFormField.java
/**
     * <a href="https://stackoverflow.com/questions/46433388/pdfbox-could-not-find-font-helv">
     * PDFbox Could not find font: /Helv
     * </a>
     * <br/>
     * <a href="https://drive.google.com/file/d/0B2--NSDOiujoR3hOZFYteUl2UE0/view?usp=sharing">
     * 4.pdf
     * </a>
     * <p>
     * The cause is a combination of the OP and the source PDF not providing
     * a default appearance for the text field and PDFBox providing defaults
     * inconsequentially.
     * </p>
     * <p>
     * This is fixed here by setting the default appearance explicitly.
     * </p>
     */
    @Test
    public void testAddFieldLikeEugenePodoliako() throws IOException {
        try (   InputStream originalStream = getClass().getResourceAsStream("4.pdf") )
        {
            PDDocument pdf = Loader.loadPDF(originalStream);
            PDDocumentCatalog docCatalog = pdf.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();
            PDPage page = pdf.getPage(0);

            PDTextField textBox = new PDTextField(acroForm);
            textBox.setPartialName("SampleField");
            acroForm.getFields().add(textBox);
            PDAnnotationWidget widget = textBox.getWidgets().get(0);
            PDRectangle rect = new PDRectangle(0, 0, 0, 0);
            widget.setRectangle(rect);
            widget.setPage(page);
//  Unnecessary code from OP
//            widget.setAppearance(acroForm.getFields().get(0).getWidgets().get(0).getAppearance());
//  Fix added to set default appearance accordingly
            textBox.setDefaultAppearance(acroForm.getFields().get(0).getCOSObject().getString("DA"));

            widget.setPrinted(false);

            page.getAnnotations().add(widget);

            acroForm.refreshAppearances();
            acroForm.flatten();
            pdf.save(new File(RESULT_FOLDER, "4-add-field.pdf"));
            pdf.close();
        }
    }
 
源代码28 项目: Knowage-Server   文件: PDFCreator.java
private static void writePageNumbering(PDDocument doc, PDFont font, float fontSize, PageNumbering pageNumbering) throws IOException {
	int totalPages = doc.getNumberOfPages();
	int numberOfPages = pageNumbering.isLastIncluded() ? doc.getNumberOfPages() : doc.getNumberOfPages() - 1;
	for (int pageIndex = pageNumbering.isFirstIncluded() ? 0 : 1; pageIndex < numberOfPages; pageIndex++) {
		String footer = "Page " + (pageIndex + 1) + " of " + totalPages;
		PDPage page = doc.getPage(pageIndex);
		PDRectangle pageSize = page.getMediaBox();
		float stringWidth = font.getStringWidth(footer) * fontSize / 1000f;
		float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

		int rotation = page.getRotation();
		boolean rotate = rotation == 90 || rotation == 270;
		float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
		float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
		float startX = rotate ? pageHeight / 2f : (pageWidth - stringWidth - stringHeight) / 2f;
		float startY = rotate ? (pageWidth - stringWidth) : stringHeight;

		// append the content to the existing stream
		try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {

			// draw rectangle
			contentStream.setNonStrokingColor(255, 255, 255); // gray background
			// Draw a white filled rectangle
			drawRect(contentStream, Color.WHITE, new java.awt.Rectangle((int) startX, (int) startY - 3, (int) stringWidth + 2, (int) stringHeight), true);
			writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, footer);
		}
	}
}
 
源代码29 项目: gcs   文件: PDAnnotationMarkup.java
/**
 * This will get the rectangle difference rectangle. Giving the difference between the
 * annotations rectangle and where the drawing occurs. (To take account of any effects applied
 * through the BE entry for example)
 *
 * @return the rectangle difference
 */
public PDRectangle getRectDifference()
{
    COSBase base = getCOSObject().getDictionaryObject(COSName.RD);
    if (base instanceof COSArray)
    {
        return new PDRectangle((COSArray) base);
    }
    return null;
}
 
源代码30 项目: testarea-pdfbox2   文件: AddImage.java
/**
 * <a href="https://stackoverflow.com/questions/50988007/clip-an-image-with-pdfbox">
 * Clip an image with PDFBOX
 * </a>
 * <p>
 * This test demonstrates how to clip an image and frame the clipping area.
 * </p>
 */
@SuppressWarnings("deprecation")
@Test
public void testImageAddClipped() throws IOException {
    try (   InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = new PDDocument();
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

        PDPage page = new PDPage();
        doc.addPage(page);
        PDRectangle cropBox = page.getCropBox();
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        contentStream.setStrokingColor(25, 200, 25);
        contentStream.setLineWidth(4);
        contentStream.moveTo(cropBox.getLowerLeftX(), cropBox.getLowerLeftY() + h/2);
        contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + 2*h/3);
        contentStream.lineTo(cropBox.getLowerLeftX() + w, cropBox.getLowerLeftY() + h/2);
        contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + h/3);
        contentStream.closePath();
        //contentStream.clip();
        contentStream.appendRawCommands("W ");
        contentStream.stroke();

        contentStream.drawImage(pdImage, cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), w, h);

        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "image-clipped.pdf"));
        doc.close();
    }
}