pdfbox如何裁剪pdf
时间: 2023-10-18 17:06:40 浏览: 153
pdfbox切图
使用 Apache PDFBox 可以很方便地裁剪 PDF。以下是一个示例程序,演示如何使用 PDFBox 裁剪 PDF:
```java
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageXYZDestination;
import org.apache.pdfbox.util.Matrix;
public class PdfCropper {
public static void main(String[] args) throws IOException {
String inputFileName = "input.pdf";
String outputFileName = "output.pdf";
// Create a PDF parser and parse the input file
PDFParser parser = new PDFParser(new File(inputFileName));
parser.parse();
// Load the parsed document
PDDocument document = parser.getPDDocument();
// Get the first page of the document
PDPage page = document.getPage(0);
// Set the crop box to be a smaller rectangle
PDRectangle cropBox = new PDRectangle(72, 72, 468, 648);
page.setCropBox(cropBox);
// Set the media box to be the same as the crop box
PDRectangle mediaBox = new PDRectangle(cropBox.getWidth(), cropBox.getHeight());
page.setMediaBox(mediaBox);
// Set the page display mode to fit the width of the screen
PDPageFitWidthDestination fitWidth = new PDPageFitWidthDestination();
fitWidth.setPageNumber(0);
page.setDisplayMode(PDPageFitWidthDestination.DISPLAY_MODE_FIT_WIDTH);
// Set the page zoom to 100%
PDPageXYZDestination xyz = new PDPageXYZDestination();
xyz.setPageNumber(0);
xyz.setZoom(1.0f);
page.setCurrentZoom(1.0f);
// Set the page background color to white
PDColor white = new PDColor(new float[]{1, 1, 1}, PDDeviceRGB.INSTANCE);
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
graphicsState.setNonStrokingColor(white);
PDGraphicsState state = new PDGraphicsState();
state.setNonStrokingColorSpace(PDDeviceRGB.INSTANCE);
state.setNonStrokingColor(white);
state.setStrokingColorSpace(PDDeviceRGB.INSTANCE);
state.setStrokingColor(white);
page.setGraphicsStateParameters(state, graphicsState);
// Save the modified document
document.save(outputFileName);
// Close the document
document.close();
}
}
```
此示例程序使用 `setCropBox()` 方法将 PDF 的裁剪框设置为 `(72, 72, 468, 648)`,这意味着裁剪框的左下角在 `(72, 72)`,右上角在 `(72+468, 72+648)`。然后使用 `setMediaBox()` 方法将媒体框设置为与裁剪框相同的大小。页面显示模式设置为适合屏幕宽度,页面缩放设置为 100%,页面背景色设置为白色。最后,使用 `save()` 方法保存修改后的文档。
阅读全文