1
Im能夠使用itext庫成功將圖像轉換爲pdf,但問題出在轉換時,它沒有正確轉換(即,)精確圖像的位置像這樣向下拖動。使用itext庫將圖像轉換爲pdf文件
這是PDF圖像....
和轉換我的形象回到PDF後,這是我得到
這是使用
代碼IM從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);
}
thanx分配花花公子這樣一個簡單的答案,它爲我工作thanx分配花花公子:) –
congrates,你懂了... –
如果你從這個答案手段得到你的解決方案,接受這個答案保持它在解決問題.. –