我正在使用itextpdf版本5.0.1将页面切割成指定的页码。当我尝试剪切以横向为导向的PDF时遇到问题。当我使用下面的代码时,面向横向的pdf将会像potrait pdf一样被截断,其余的则不见了。我使用的代码是:iText PDF方向
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFSplitExample {
static void splitPdfFile(InputStream inputPdf,
OutputStream outputStream, int startPage,
int endPage) throws Exception{
//Create document and pdfReader objects.
Document document = new Document();
PdfReader pdfReader = new PdfReader(inputPdf);
//Get total no. of pages in the pdf file.
int totalPages = pdfReader.getNumberOfPages();
//Check the startPage should not be greater than the endPage
//and endPage should not be greater than total no. of pages.
if(startPage > endPage || endPage > totalPages) {
System.out.println("Kindly pass the valid values " +
"for startPage and endPage.");
}else{
// Create writer for the outputStream
PdfWriter writer =
PdfWriter.getInstance(document, outputStream);
//Open document
document.open();
//Contain the pdf data.
PdfContentByte pdfContentByte =
writer.getDirectContent();
PdfImportedPage page;
while(startPage <= endPage) {
document.newPage();
page=writer.getImportedPage(pdfReader, startPage);
pdfContentByte.addTemplate(page, 0, 0);
startPage++;
}
//Close document and outputStream.
outputStream.flush();
document.close();
outputStream.close();
}
}
public static void main(String args[]){
try {
//Prepare output stream for
//new pdf file after split process.
OutputStream outputStream1 =
new FileOutputStream("SplitFile1.pdf");
OutputStream outputStream2 =
new FileOutputStream("SplitFile2.pdf");
//call method to split pdf file.
splitPdfFile(new FileInputStream("TestFile.pdf"),
outputStream1, 1, 10);
splitPdfFile(new FileInputStream("TestFile.pdf"),
outputStream2, 11, 20);
System.out.println("Pdf file splitted successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
对于你的任务,你真的应该使用'PdfCopy'基于实现(除其它优势外并不需要你控制页面旋转),而不是你的'PdfWriter'的基础一。 – mkl
我无法得到你想说的话。你能否更详细地解释一下? –