我能够成功地使用itext库将图像转换为pdf,但问题是在转换时没有正确转换(即),确切图像的位置正在向下拖动。
这是pdf图像....
将我的图像转换回pdf后,这就是我得到的
这是使用
的代码用于从pdf转换为图像
File sourceFile = new File(sourceDir);
File destinationFile = new File(destinationDir);
String fileName = sourceFile.getName().replace(".pdf", "");
if (sourceFile.exists()) {
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("Folder created in: "+ destinationFile.getCanonicalPath());
}
RandomAccessFile raf = new RandomAccessFile(sourceFile, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdf = new PDFFile(buf);
System.out.println("Total Pages: "+ pdf.getNumPages());
int pageNumber = 1;
for (int i = 0; i < pdf.getNumPages(); i++) {
PDFPage page = pdf.getPage(i+1);
// image dimensions
int width = 1200;
int height = 1400;
// create the image
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// width & height, // clip rect, // null for the ImageObserver, // fill background with white, // block until drawing is done
Image image = page.getImage(width, height, rect, null, true, true );
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
File imageFile = new File( destinationDir + "pdfImg" + i +".png" );// change file format here. Ex: .png, .jpg, .jpeg, .gif, .bmp
ImageIO.write(bufferedImage, "png", imageFile);
pageNumber++;
}
}
这是我用来将其转换回pdf的代码
Rectangle pageSize = new Rectangle(2780, 2525);
Document pdfDocument = new Document(PageSize.A4);
String pdfFilePath = outputFile;
try
{
FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
PdfWriter writer = null;
writer = PdfWriter.getInstance(pdfDocument, fileOutputStream);
writer.open();
pdfDocument.open();
/**
* Proceed if the file given is a picture file
*/
if (isPictureFile)
{
pdfDocument.add(com.itextpdf.text.Image.getInstance(inputFile));
}
/**
* Proceed if the file given is (.txt,.html,.doc etc)
*/
else
{
File file = new File(inputFile);
//pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file)));
}
pdfDocument.close();
writer.close();
}
catch (Exception exception)
{
System.out.println("Document Exception!" + exception);
}
答案 0 :(得分:4)
在此更改图片尺寸:
// image dimensions
int width = 700; // here
int height = 600;//here
您的图片超出了pdf screenSize ...将其缩小为pdf中接受的内容..