2010-09-10 93 views
2

我需要創建一個在線查看器,將PDF文件轉換爲可瀏覽的圖像,如http://view.samurajdata.se/。我想在Grails中這樣做。 Grails是否有插件?如何將PDF轉換爲網頁瀏覽圖像?

+0

這可能只是我,但我真的不知道你是什麼其實是問這裏... – peSHIr 2010-09-10 08:31:03

+0

在我的項目用戶有要求他可以上傳PDF文件,並將其轉換爲grails中的圖像文件 – 2010-09-10 10:07:42

+0

請參閱http://stackoverflow.com/questions/550129/export-pdf-pages-to-a-series-of-images- in-java 這是一個java精靈! – 2013-12-25 10:56:57

回答

0

這可以通過下載PDFRenderer.jar外商投資企業和編寫代碼如下

downloadedfile = request.getFile('sourceFile'); 
println "download file->"+downloadedfile 
File destFile=new File('web-app/source-pdf/'+downloadedfile+'.pdf'); 

if(destFile.exists()){ 

    destFile.delete(); 

} 

File file = null; 
try{ 
    file = new File('web-app/source-pdf/'+downloadedfile+'.pdf'); 
    downloadedfile.transferTo(file) 
    println "file->"+file 
}catch(Exception e){ 
    System.err.println("File Already Use") 

    //out.close(); 
} 

File imageFile=new File("web-app/pdf-images"); 

    if(imageFile.isDirectory()) 
    { 
     String[] list=imageFile.list() 

    for(int i=0;i<list.length;i++){ 
     File img=new File("web-app/pdf-images/"+i+".png") 
     img.delete() 

    } 
    } 
    //response.setContentType("image/png"); 
    // response.setHeader("Cache-control", "no-cache"); 

    RandomAccessFile raf; 
    BufferedImage[] img; 

    // response.setContentType("image/png"); 
     // response.setHeader("Cache-control", "no-cache"); 





    file=new File('web-app/source-pdf/'+downloadedfile+'.pdf'); 

    try { 
     raf = new RandomAccessFile(file, "rws"); 

     FileChannel channel = raf.getChannel(); 
     ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size()); 
     PDFFile pdffile = new PDFFile(buf); 
     // draw the first page to an image 
     int num=pdffile.getNumPages(); 
     img=new BufferedImage[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,(int)rect.height,(int)rect.width); 


      //generate the image 
      img[i] = (BufferedImage)page.getImage(
         width,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[i], "png",new File("web-app/pdf-images/"+i+".png")); 
     } 

    // out.close(); 
    } 
    catch (FileNotFoundException e1) { 
     System.err.println(e1.getLocalizedMessage()); 
    } catch (IOException e) { 
     System.err.println(e.getLocalizedMessage()); 
    } 
    file = null; 
    render(view:'save',model:[images:img])