本文整理匯總了Java中org.apache.pdfbox.pdmodel.PDDocument類的典型用法代碼示例。如果您正苦於以下問題:Java PDDocument類的具體用法?Java PDDocument怎麽用?Java PDDocument使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
PDDocument類屬於org.apache.pdfbox.pdmodel包,在下文中一共展示了PDDocument類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: createAlternateRowsDocument
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
@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();
}
示例2: createRingManagerDocument
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
@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();
}
示例3: removeText
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
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;
}
示例4: process
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
private boolean process() throws IOException {
boolean toReturn = false;
PDFTextStripper stripper = new TitleExtractor();
PDDocument document = null;
try {
document = PDDocument.load(new File(this.getFileNamePathWithExtension()));
//((TitleExtractor) stripper).setFileNamePathWithExtension(this.getFileNamePathWithExtension());
stripper.setSortByPosition(true);
stripper.setStartPage(0);
stripper.setEndPage(1);
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
setTitle(((TitleExtractor) stripper).getTitle());
toReturn = true;
} finally {
if (document != null) {
document.close();
}
}
return toReturn;
}
示例5: printDocument
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
public static void printDocument() throws IOException, PrinterException
{
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(Sides.TWO_SIDED_SHORT_EDGE);
PDDocument input = PDDocument.load(new File("Karteikarten.pdf"));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(input));
if (job.printDialog(pras)) {
job.print(pras);
}
}
示例6: transformTextAndCheck
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
private void transformTextAndCheck(String text, String encoding, String checkText)
throws IOException
{
// Get a reader for the text
ContentReader reader = buildContentReader(text, Charset.forName(encoding));
// And a temp writer
File out = TempFileProvider.createTempFile("AlfrescoTest_", ".pdf");
ContentWriter writer = new FileContentWriter(out);
writer.setMimetype("application/pdf");
// Transform to PDF
transformer.transform(reader, writer);
// Read back in the PDF and check it
PDDocument doc = PDDocument.load(out);
PDFTextStripper textStripper = new PDFTextStripper();
StringWriter textWriter = new StringWriter();
textStripper.writeText(doc, textWriter);
doc.close();
String roundTrip = clean(textWriter.toString());
assertEquals(
"Incorrect text in PDF when starting from text in " + encoding,
checkText, roundTrip
);
}
示例7: render
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
/**
* 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;
}
示例8: testMultiPageJFreeChart
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
@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();
}
示例9: createSampleDocument
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
@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();
}
示例10: setMetadata
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
public void setMetadata(PDDocument doc) throws Exception {
PDDocumentCatalog catalog = doc.getDocumentCatalog();
PDDocumentInformation info = doc.getDocumentInformation();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(now);
XMPMetadata metadata = new XMPMetadata();
XMPSchemaPDF pdfSchema = metadata.addPDFSchema();
pdfSchema.setKeywords(info.getKeywords());
pdfSchema.setProducer(info.getProducer());
XMPSchemaBasic basicSchema = metadata.addBasicSchema();
basicSchema.setModifyDate(cal);
basicSchema.setCreateDate(cal);
basicSchema.setCreatorTool(info.getCreator());
basicSchema.setMetadataDate(cal);
XMPSchemaDublinCore dcSchema = metadata.addDublinCoreSchema();
dcSchema.setTitle(info.getTitle());
dcSchema.addCreator("PDFBox");
dcSchema.setDescription(info.getSubject());
PDMetadata metadataStream = new PDMetadata(doc);
metadataStream.importXMPMetadata(metadata);
catalog.setMetadata(metadataStream);
}
示例11: createBookPage
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
/**
* 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;
}
示例12: findPhoto
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
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();
}
示例13: createPage
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
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);
}
}
示例14: saveDocument
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
@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();
}
}
}
示例15: main
import org.apache.pdfbox.pdmodel.PDDocument; //導入依賴的package包/類
public static void main(String[] args) {
try {
PDDocument document = PDDocument.load(new File("PDF File.pdf"));
PDFTextStripper Tstripper = new PDFTextStripper();
String documentText = Tstripper.getText(document);
System.out.println(documentText);
} catch (Exception e) {
e.printStackTrace();
}
}