2011-05-28 199 views
9

可能重复:
Convert pdf file to jpg asp.netPDF格式的图像转换

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

你能提供完整的调用堆栈吗? – 2011-05-28 06:21:30

+1

您是否可以使用Acrobat,IcePDF和其他pdf查看器查看PDF?还是他们也提出警告/错误? – extraneon 2011-05-28 13:22:19

回答

3

在野外有很多格式不正常的PDF文件,这很可能是其中之一。

直到看到问题PDF文件时才能给出明确的答案。我猜测是'startxref'指定了外部参照表应该位于PDF中的绝对位置。 java库正在跳转到文件的这个位置,希望找到单词“xref”但找不到它。解决这个问题

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

的一种方法是将文件加载到Acrobat中的完整版本,然后保存文件。 Acrobat将修正链接中提到的外部参照偏移量。

有相当大的公司在那里产生畸形的PDF应该知道更好。 Adobe允许这些文件存在,因为它使得其PDF竞争对手难以保持竞争力。