Java Code Examples for org.apache.pdfbox.pdmodel.PDDocument.save()

The following are Jave code examples for showing how to use save() of the org.apache.pdfbox.pdmodel.PDDocument class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: easytable   File: TableDrawerIntegrationTest.java   Source Code and License Vote up 12 votes
@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 Vote up 11 votes
@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: easytable   File: TableDrawerIntegrationTest.java   Source Code and License Vote up 8 votes
@Test
public void createSampleDocument() throws Exception {
    // Define the table structure first
    TableBuilder tableBuilder = new TableBuilder()
            .addColumnOfWidth(300)
            .addColumnOfWidth(120)
            .addColumnOfWidth(70)
            .setFontSize(8)
            .setFont(PDType1Font.HELVETICA);

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

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

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

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

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

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

    document.save("target/sampleWithColorsAndBorders.pdf");
    document.close();
}
 
Example 4
Project: pdfbox-graphics2d   File: MultiPageTest.java   Source Code and License Vote up 8 votes
@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 5
Project: FYS_T3   File: statisticsController.java   Source Code and License Vote up 7 votes
@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 6
Project: pdfjumbler   File: PdfEditor.java   Source Code and License Vote up 6 votes
@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 7
Project: campingsimulator2017   File: ReservationsController.java   Source Code and License Vote up 6 votes
/**
 * @param facture
 * @throws IOException
 * export the bill as pdf
 */
public void exportFacturePDF(PDDocument facture) throws IOException {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Exporter la facture");
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Portable Document Format", "*.pdf"));
    File selectedFile = fileChooser.showSaveDialog(homeController.getView().getWindow());

    facture.save(selectedFile);
}
 
Example 8
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DTestBase.java   Source Code and License Vote up 6 votes
@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 9
Project: PrintDF   File: PrintDF.java   Source Code and License Vote up 6 votes
public static void createBooklet(File f, BookletSettings setts) {
	try {
		PDDocument document = PDDocument.load(f);
		
		if (document.isEncrypted()) {
			System.err.println("Error: Encrypted documents are not supported!");
			System.exit(1);
		}
		
		PageSize size = setts.getSize().getPageSize();
		size.setOrientation(Orientation.LANDSCAPE);
		
		BookletMaker.setSizeOverride(size);			
		BookletMaker.setScale(setts.getScale());
		
		PDDocument booklet = BookletMaker.make(document);
		
		if(setts.isRotateEvens())
			BookletRotater.flip(booklet, PageSelector.pagesEven(booklet));
		
		String name = setts.getDirectory(f);
		System.out.println(name);

		booklet.save(name);
		document.close();
	}
	catch(IOException e) {
		e.printStackTrace();
	}
}
 
Example 10
Project: Lernkartei_2017   File: Printer.java   Source Code and License Vote up 4 votes
public static void giveToPrint(String stack) throws Exception {
	deleteFile();
	setValues(stack);
	pages = calculatePages(content.size());
	printContent();
	for (int i = 0; i < pages; i++) { 
		if (i == 0) {
	
			PDDocument doc = new PDDocument();
			doc.save(fileName);
			doc.close();
			
			
			
			cacheAll = content;
		}

		PDDocument doc2 = PDDocument.load(new File(fileName));
		
		cacheSpezific = createCaheSpezific(cacheAll);


		createPage(doc2,2);
		//int pages = doc2.getDocumentCatalog().getAllPages().size();
		
		drawLines(doc2,actualPage);
		drawText(doc2,actualPage);
		
		actualPage+=2;
		//finalDoc = doc2;
		
		doc2.save(fileName);
		doc2.close();

		print();
	}
	
	
	printDocument();
}