java - PDF到图像转换

标签 java image exception pdf converter

<分区>

Possible Duplicate:
Convert pdf file to jpg asp.net

public class Pdf2Image {

    private Image image;
    int length;
    public int convertPdf2Image(String pdfname) {
        File file = new File(pdfname);
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            // draw the first page to an image
            int num = pdffile.getNumPages();

            length=num;
            for (int i = 0; i <= num; i++) {
                PDFPage page = pdffile.getPage(i);
                //get the width and height for the doc at the default zoom
                int width = (int) page.getBBox().getWidth();
                int height = (int) page.getBBox().getHeight();
                Rectangle rect = new Rectangle(0, 0, width, height);
                int rotation = page.getRotation();
                Rectangle rect1 = rect;
                if (rotation == 90 || rotation == 270) {
                    rect1 = new Rectangle(0, 0, rect.height, rect.width);
                }
                //generate the image
                BufferedImage img = (BufferedImage) page.getImage(
                        rect.width, rect.height, //width & height
                        rect1, // clip rect
                        null, // null for the ImageObserver
                        true, // fill background with white
                        true // block until drawing is done
                        );
                ImageIO.write(img, "png", new File("src\\downloadedFiles\\aa" + i + ".png"));
            }
        } catch (FileNotFoundException e1) {
            System.err.println(e1.getLocalizedMessage());
        } catch (IOException e) {
            System.err.println(e.getLocalizedMessage());
        }
        return length;
    }

    public static void main(String[] args) {
        Pdf2Image p = new Pdf2Image();
        p.convertPdf2Image("src\\downloadedFiles\\todaypdf.pdf");
    }
}

我正在使用此代码将 PDF 文件转换为图像。它适用于大多数 PDF,但显示 PDF 文件异常。异常(exception)是:

Expected 'xref' at start of table.

谁能告诉我为什么会出现这样的异常?

最佳答案

在野外有许多格式错误的 PDF 文件,这很可能是其中之一。

在看到问题PDF文件之前,无法给出明确的答案。我的猜测是“startxref”在 PDF 中指定了外部参照表所在位置的绝对位置。 java 库跳转到文件中的这个位置,希望找到单词“xref”,但找不到。

http://blog.amyuni.com/?p=1627

解决此问题的一种方法是将文件加载到完整版 Acrobat 中,然后保存文件。 Acrobat 将修复链接中提到的外部参照偏移。

有相当多的大公司生成格式错误的 PDF,他们应该更清楚。 Adobe 允许这些文件存在,因为这让他们的 PDF 竞争对手难以跟上和竞争。

关于java - PDF到图像转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6160031/

相关文章:

java - 相应的 try block 中永远不会抛出异常

exception - 如何找到 "ignored"的异常?

Java(声音)- 将 2D int 数组转换为字节数组

java - JTable 从末尾选择行

java - 在 java 中获取变量值的问题。变量的范围

java - 获取通用类的.class对象

iOS - 图像大小与 ImageView 大小

c++ - 我可以扔流吗?

php - 在php中从头开始创建带有文本的透明png

python - 边缘检测后从各个方向裁剪图像