PDF转图像转换

9

可能重复:
将pdf文件转换为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文件中会出现异常。异常信息如下:

Expected 'xref' at start of table.

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


2
你能提供完整的调用堆栈吗? - Zian Choy
1
你能使用Acrobat、IcePDF或者其他PDF阅读器查看PDF吗?还是它们也会显示警告/错误信息? - extraneon
1个回答

3

现在有很多格式不规范的PDF文件,很可能这就是其中之一。

在看到具体问题的PDF文件之前,不可能给出明确的答案。我猜测 'startxref' 指定了PDF中xref表所在的绝对位置。Java库会跳转到该位置,并期望找到 'xref' 这个词,但是却找不到它。

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

解决这个问题的一种方法是将文件加载到Acrobat的完整版本中,然后保存该文件。如链接所述,Acrobat将修复xref偏移量。

有很多大公司生成格式不正确的PDF文件,他们应该知道更好的做法。Adobe允许这些文件存在,因为这使得其他PDF竞争对手难以跟上并竞争。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接