Java Code Examples for com.lowagie.text.pdf.PdfReader#getNumberOfPages()

The following examples show how to use com.lowagie.text.pdf.PdfReader#getNumberOfPages() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PdfContentReaderTool.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Writes information about each page in a PDF file to the specified output stream.
 * 
 * @since 2.1.5
 * @param pdfFile a File instance referring to a PDF file
 * @param out the output stream to send the content to
 * @throws IOException
 */
static public void listContentStream(File pdfFile, PrintWriter out) throws IOException {
	PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());

	int maxPageNum = reader.getNumberOfPages();

	for (int pageNum = 1; pageNum <= maxPageNum; pageNum++) {
		listContentStreamForPage(reader, pageNum, out);
	}

}
 
Example 2
Source File: PdfContentReaderTool.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Writes information about each page in a PDF file to the specified output stream.
 * @since 2.1.5
 * @param pdfFile	a File instance referring to a PDF file
 * @param out       the output stream to send the content to
 * @throws IOException
 */
static public void listContentStream(File pdfFile, PrintWriter out) throws IOException {
    PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
        
    int maxPageNum = reader.getNumberOfPages();
    
    for (int pageNum = 1; pageNum <= maxPageNum; pageNum++){
        listContentStreamForPage(reader, pageNum, out);
    }       
        
}
 
Example 3
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
public String cropPdf(String pdfFilePath) throws DocumentException, IOException, Exception {
	String filename = FilenameUtils.getBaseName(pdfFilePath) + "_cropped." + FilenameUtils.getExtension(pdfFilePath);
	filename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename);
	PdfReader reader = new PdfReader(pdfFilePath);
	try {
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
		try {
			for (int i = 1; i <= reader.getNumberOfPages(); i++) {
				PdfDictionary pdfDictionary = reader.getPageN(i);
				PdfArray cropArray = new PdfArray();
				Rectangle box = getSmallestBox(reader, i);
				//Rectangle cropbox = reader.getCropBox(i);
				if (box != null) {
					cropArray.add(new PdfNumber(box.getLeft()));
					cropArray.add(new PdfNumber(box.getBottom()));
					cropArray.add(new PdfNumber(box.getLeft() + box.getWidth()));
					cropArray.add(new PdfNumber(box.getBottom() + box.getHeight()));
					pdfDictionary.put(PdfName.CROPBOX, cropArray);
					pdfDictionary.put(PdfName.MEDIABOX, cropArray);
					pdfDictionary.put(PdfName.TRIMBOX, cropArray);
					pdfDictionary.put(PdfName.BLEEDBOX, cropArray);
				}
			}
			return filename;
		} finally {
			stamper.close();
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw e;
	} finally {
		reader.close();
	}
}
 
Example 4
Source File: TrialBalanceReportAction.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generate pdf for sending response using itext
 *
 * @param reportFileFullName
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws BadPdfFormatException
 */
protected ByteArrayOutputStream generatePdfOutStream(String reportFileFullName) throws IOException, DocumentException, BadPdfFormatException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // we create a reader for a certain document
    PdfReader reader = new PdfReader(reportFileFullName);
    reader.consolidateNamedDestinations();

    // step 1: creation of a document-object
    Document document = new Document(reader.getPageSizeWithRotation(1));
    // step 2: we create a writer that listens to the document
    PdfCopy writer = new PdfCopy(document, baos);
    // step 3: we open the document
    document.open();

    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();

    // step 4: we add content
    PdfImportedPage page;
    for (int i = 0; i < n;) {
        ++i;
        page = writer.getImportedPage(reader, i);
        writer.addPage(page);
    }
    writer.freeReader(reader);

    // step 5: we close the document
    document.close();
    return baos;
}
 
Example 5
Source File: SplitPdf.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * This class can be used to split an existing PDF file.
 * @param args the command line arguments
 */
public static void main(String args[]) {
    if (args.length != 4) {
        System.err.println("arguments: srcfile destfile1 destfile2 pagenumber");
    }
    else {
        try {
int pagenumber = Integer.parseInt(args[3]);
            
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
            
if (pagenumber < 2 || pagenumber > n) {
	throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page.");
}
            
// step 1: creation of a document-object
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1]));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2]));
// step 3: we open the document
document1.open();
PdfContentByte cb1 = writer1.getDirectContent();
document2.open();
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < pagenumber - 1) {
	i++;
	document1.setPageSize(reader.getPageSizeWithRotation(i));
	document1.newPage();
	page = writer1.getImportedPage(reader, i);
	rotation = reader.getPageRotation(i);
	if (rotation == 90 || rotation == 270) {
		cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
	}
	else {
		cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
	}
}
while (i < n) {
	i++;
	document2.setPageSize(reader.getPageSizeWithRotation(i));
	document2.newPage();
	page = writer2.getImportedPage(reader, i);
	rotation = reader.getPageRotation(i);
	if (rotation == 90 || rotation == 270) {
		cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
	}
	else {
		cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
	}
	System.out.println("Processed page " + i);
}
// step 5: we close the document
document1.close();
document2.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 6
Source File: AddWatermarkPageNumbersTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * Reads the pages of an existing PDF file, adds pagenumbers and a watermark.

    */
@Test
   public  void main() throws Exception {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR +"ChapterSection.pdf");
           int n = reader.getNumberOfPages();
           // we create a stamper that will copy the document to a new file
           PdfStamper stamp = new PdfStamper(reader,PdfTestBase.getOutputStream("watermark_pagenumbers.pdf"));
           // adding some metadata
           HashMap<String, String> moreInfo = new HashMap<String, String>();
           moreInfo.put("Author", "Bruno Lowagie");
           stamp.setMoreInfo(moreInfo);
           // adding content to each page
           int i = 0;
           PdfContentByte under;
           PdfContentByte over;
           Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR +"watermark.jpg");
           BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
           img.setAbsolutePosition(200, 400);
           while (i < n) {
           	i++;
           	// watermark under the existing page
           	under = stamp.getUnderContent(i);
           	under.addImage(img);
           	// text over the existing page
           	over = stamp.getOverContent(i);
           	over.beginText();
           	over.setFontAndSize(bf, 18);
           	over.setTextMatrix(30, 30);
           	over.showText("page " + i);
           	over.setFontAndSize(bf, 32);
           	over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
           	over.endText();
           }
           // adding an extra page
           stamp.insertPage(1, PageSize.A4);
           over = stamp.getOverContent(1);
       	over.beginText();
       	over.setFontAndSize(bf, 18);
           over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
           over.endText();
           // adding a page from another document
           PdfReader reader2 = new PdfReader(PdfTestBase.RESOURCES_DIR +"SimpleAnnotations1.pdf");
           under = stamp.getUnderContent(1);
           under.addTemplate(stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
           // closing PdfStamper will generate the new PDF file
           stamp.close();
   }
 
Example 7
Source File: TwoOnOneTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Reads the pages of an existing PDF file and puts 2 pages from the
 * existing doc into one of the new doc.
 */
@Test
public void main() throws Exception {
	// we create a reader for a certain document
	PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR + "ChapterSection.pdf");
	// we retrieve the total number of pages
	int n = reader.getNumberOfPages();
	// we retrieve the size of the first page
	Rectangle psize = reader.getPageSize(1);
	float width = psize.getHeight();
	float height = psize.getWidth();

	// step 1: creation of a document-object
	Document document = new Document(new Rectangle(width, height));
	// step 2: we create a writer that listens to the document
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("2on1.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we add content
	PdfContentByte cb = writer.getDirectContent();
	int i = 0;
	int p = 0;
	while (i < n) {
		document.newPage();
		p++;
		i++;
		PdfImportedPage page1 = writer.getImportedPage(reader, i);
		cb.addTemplate(page1, .5f, 0, 0, .5f, 60, 120);
		if (i < n) {
			i++;
			PdfImportedPage page2 = writer.getImportedPage(reader, i);
			cb.addTemplate(page2, .5f, 0, 0, .5f, width / 2 + 60, 120);
		}
		BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
		cb.beginText();
		cb.setFontAndSize(bf, 14);
		cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 2) + (n % 2 > 0 ? 1 : 0)),
				width / 2, 40, 0);
		cb.endText();
	}
	// step 5: we close the document
	document.close();

}
 
Example 8
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
private String createOneUp(String originalPdfFile) throws IOException, DocumentException {
	logger.debug("Started create 1-up file from " + originalPdfFile);
	String filename = FilenameUtils.getBaseName(originalPdfFile) + "_1up." + FilenameUtils.getExtension(originalPdfFile);
	String tempFilename =  FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp");
	filename = FilenameUtils.concat(getPdfFileFolder(), filename);
	File tempFile = new File(tempFilename);
	//float scale = 0.80f;
	PdfReader reader = new PdfReader(originalPdfFile);
	Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
	//Document doc = new Document(new RectangleReadOnly(606.96f, 850.32f), 0, 0, 0, 0);
	PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
	doc.open();
	for (int i = 1; i <= reader.getNumberOfPages(); i++) {
		doc.newPage();
		PdfContentByte cb = writer.getDirectContent();
		PdfImportedPage page = writer.getImportedPage(reader, i);
		
		
		float documentWidth = doc.getPageSize().getWidth();
		float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}
		
		
		/*float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}
		float documentWidth = doc.getPageSize().getWidth();*/

		float pageWidth = page.getWidth();
		float pageHeight = page.getHeight();
		
		float widthScale = documentWidth / pageWidth;
		float heightScale = documentHeight / pageHeight;
		float scale = Math.min(widthScale, heightScale);
		
		float offsetX = (documentWidth - (pageWidth * scale)) / 2;
		float offsetY = 0f;
		if (i > 1) {
			offsetY = 65f;
		}
		/*
		
		float offsetX = 0f;
		if (i > 1) {
			offsetX = 65f; //100f
		}
		//float offsetX = 65f;
		float offsetY = ((documentHeight) - (pageHeight * scale)) / 2;*/
		
		cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);

	}
	doc.close();
	overlayLicenceArea(tempFilename, filename, PageLayout.ONE_UP);
	logger.debug("Deleting temporary file " + tempFile.getAbsolutePath());
	FileUtils.deleteQuietly(tempFile);
	logger.debug("Completed create 1-up file from " + originalPdfFile);
	return filename;
}
 
Example 9
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
private String createTwoUp(String originalPdfFile) throws IOException, DocumentException {
	logger.debug("Started create 2-up file from " + originalPdfFile);
	String filename = FilenameUtils.getBaseName(originalPdfFile) + "_2up." + FilenameUtils.getExtension(originalPdfFile);
	String tempFilename =  FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp");
	filename = FilenameUtils.concat(getPdfFileFolder(), filename);
	File tempFile = new File(tempFilename);
	//float scale = 0.60f;
	PdfReader reader = new PdfReader(originalPdfFile);
	Document doc = new Document(new RectangleReadOnly(842f, 595f), 0, 0, 0, 0);
	//Document doc = new Document(new RectangleReadOnly(850.32f, 606.96f), 0, 0, 0, 0);
	//doc.setMargins(50f, 50f, 50f, 50f);
	PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
	doc.open();
	int totalPages = reader.getNumberOfPages();
	for (int i = 1; i <= totalPages; i = i + 2) {
		doc.newPage();
		PdfContentByte cb = writer.getDirectContent();
		PdfImportedPage page = writer.getImportedPage(reader, i); // page #1
		
		float documentWidth = doc.getPageSize().getWidth() / 2;
		float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}

		float pageWidth = page.getWidth();
		float pageHeight = page.getHeight();
		
		float widthScale = documentWidth / pageWidth;
		float heightScale = documentHeight / pageHeight;
		float scale = Math.min(widthScale, heightScale);
		
		//float offsetX = 50f;
		float offsetX = (documentWidth - (pageWidth * scale)) / 2;
		float offsetY = 0f;
		if (i > 1) {
			offsetY = 65f; //100f
		}
		
		cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);
		
		if (i+1 <= totalPages) {
		
			PdfImportedPage page2 = writer.getImportedPage(reader, i+1); // page #2
			
			pageWidth = page.getWidth();
			pageHeight = page.getHeight();
			
			widthScale = documentWidth / pageWidth;
			heightScale = documentHeight / pageHeight;
			scale = Math.min(widthScale, heightScale);
			
			offsetX = ((documentWidth - (pageWidth * scale)) / 2) + documentWidth;
			//offsetY = 65f; //100f
			
			cb.addTemplate(page2, scale, 0, 0, scale, offsetX, offsetY);//430f
		}
	}
	
	doc.close();
	overlayLicenceArea(tempFilename, filename, PageLayout.TWO_UP);
	logger.debug("Deleting temporary file " + tempFile.getAbsolutePath());
	FileUtils.deleteQuietly(tempFile);
	logger.debug("Completed create 2-up file from " + originalPdfFile);
	return filename;
}
 
Example 10
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
private String createA5(String originalPdfFile) throws IOException, DocumentException {
	logger.debug("Started create A5 file from " + originalPdfFile);
	String filename = FilenameUtils.getBaseName(originalPdfFile) + "_a5." + FilenameUtils.getExtension(originalPdfFile);
	String tempFilename =  FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp");
	filename = FilenameUtils.concat(getPdfFileFolder(), filename);
	File tempFile = new File(tempFilename);
	//float scale = 0.72906403940886699507389162561576f;
	PdfReader reader = new PdfReader(originalPdfFile);
	
	//new RectangleReadOnly(425.16f, 606.96f)
	Document doc = new Document(PageSize.A5, 0, 0, 0, 0);
	PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
	doc.open();
	for (int i = 1; i <= reader.getNumberOfPages(); i++) {
		doc.newPage();
		PdfContentByte cb = writer.getDirectContent();
		PdfImportedPage page = writer.getImportedPage(reader, i); // page #1
		
		float documentWidth = doc.getPageSize().getWidth();
		float documentHeight = doc.getPageSize().getHeight();
		if (i > 1) {
			documentHeight = documentHeight - 65f;
		}
		//float documentHeight = doc.getPageSize().getHeight() - 65f;

		float pageWidth = page.getWidth();
		float pageHeight = page.getHeight();
		
		float widthScale = documentWidth / pageWidth;
		float heightScale = documentHeight / pageHeight;
		float scale = Math.min(widthScale, heightScale);
		
		//float offsetX = 50f;
		float offsetX = (documentWidth - (pageWidth * scale)) / 2;
		float offsetY = 0f;
		if (i > 1) {
			offsetY = 65f;
		}
		//float offsetY = ((documentHeight) - (pageHeight * scale)) / 2;
		
		cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);
		//cb.addTemplate(page, scale, 0, 0, scale, 50f, 100f);
	}
	doc.close();
	//FileUtils.moveFile(tempFile, new File(filename));
	overlayLicenceArea(tempFilename, filename, PageLayout.A5);
	logger.debug("Deleting temporary file " + tempFile.getAbsolutePath());
	FileUtils.deleteQuietly(tempFile);
	logger.debug("Completed create A5 file from " + originalPdfFile);
	return filename;
}