2012-07-02 39 views
9

Sử dụng pdfbox hiển thị một lỗi:Làm thế nào để chuyển đổi một pdf sang một hình ảnh?

import java.awt 
import javax` 

Dựa trên đoạn mã sau:

imageType = BufferedImage.TYPE_INT_ARGB; //need to specifies java.awt 
String[] formats = ImageIO.getReaderFormatNames(); //need to specifies javax 
+0

cuối cùng tôi đã tìm thấy giải pháp ..... chúng tôi không thể sử dụng awt với Android. như vậy, cuối cùng đi cho pdf viewver lib trên http://sourceforge.net/projects/andpdf/files/ tìm ra apk và cũng nguồn cho pdf sang hình ảnh .... thenx, xin lỗi cho tiếng anh của tôi .... – Amit

Trả lời

6

Cuối cùng tôi tìm thấy giải pháp. Chúng tôi không thể sử dụng awt với Android, vì vậy, cuối cùng đi cho lib viewver pdf trên http://sourceforge.net/projects/andpdf/files/

Tìm hiểu gói ứng dụng và cũng cung cấp nguồn pdf cho hình ảnh.

Đây là myclass để chuyển đổi pdf sang hình ảnh:

package com.print; 

import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.RandomAccessFile; 
import java.nio.channels.FileChannel; 

import net.sf.andpdf.nio.ByteBuffer; 
import net.sf.andpdf.refs.HardReference; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.RectF; 
import android.os.Bundle; 
import android.os.Environment; 
import android.os.Handler; 
import android.util.Log; 
import android.widget.ImageView; 
import android.widget.TextView; 

import com.sun.pdfview.PDFFile; 
import com.sun.pdfview.PDFImage; 
import com.sun.pdfview.PDFPage; 
import com.sun.pdfview.PDFPaint; 
import com.sun.pdfview.decrypt.PDFAuthenticationFailureException; 
import com.sun.pdfview.font.PDFFont; 

public class Transformer extends Activity{ 
    ///////////////////////////////////////////// 
    private static final int STARTPAGE = 1; 
    private static final float STARTZOOM = 1.0f; 

    private static final String TAG = "PDFVIEWER"; 
    Bitmap _bitmap=null; 

// private GraphView mGraphView; 
    private String pdffilename; 
    private PDFFile mPdfFile; 
    private int mPage; 
    private float mZoom; 
    private File mTmpFile; 

    private PDFPage mPdfPage; 

    private Thread backgroundThread; 
    private Handler uiHandler; 

    ImageView myimg; 
    TextView command; 
    Context context; 
    ProgressDialog _p=null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.trans); 
     context=Transformer.this; 
      uiHandler = new Handler(); 
     initContrils(); 
    } 

    private void initContrils() { 
     // TODO Auto-generated method stub 
     boolean showImages = getIntent().getBooleanExtra(printDemo.EXTRA_SHOWIMAGES, true); 
      PDFImage.sShowImages = showImages; 
      boolean antiAlias = getIntent().getBooleanExtra(printDemo.EXTRA_ANTIALIAS, true); 
      PDFPaint.s_doAntiAlias = antiAlias; 
      boolean useFontSubstitution = getIntent().getBooleanExtra(printDemo.EXTRA_USEFONTSUBSTITUTION, false); 
      PDFFont.sUseFontSubstitution= useFontSubstitution; 
      boolean keepCaches = getIntent().getBooleanExtra(printDemo.EXTRA_KEEPCACHES, false); 
      HardReference.sKeepCaches= keepCaches; 

      if (this.getIntent() != null) { 
       pdffilename = getIntent().getStringExtra(printDemo.EXTRA_PDFFILENAME); 
     } 
     mPage = STARTPAGE; 
     mZoom = STARTZOOM; 
     myimg=(ImageView)findViewById(R.id.imageView1); 
     command=(TextView)findViewById(R.id.textView1); 
     _p=new ProgressDialog(context); 
     _p.setMessage("Converting........"); 
     _p.setCancelable(false); 
     _p.show(); 
     setContent(); 
    } 

    private void setContent() { 
     try { 
      parsePDF(pdffilename); 
      startRenderThread(mPage, mZoom); 

     } 
     catch (PDFAuthenticationFailureException e) { 
      Log.e("Amit...","Error...."); 
     } 
    } 
    private synchronized void startRenderThread(final int page, final float zoom) { 
      Log.e("Amit","renderrar"); 
     if (backgroundThread != null) 
      return; 
     backgroundThread = new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        if (mPdfFile != null) { 

         showPage(page, zoom); 
        } 
       } catch (Exception e) { 
        Log.e(TAG, e.getMessage(), e); 
       } 
       backgroundThread = null; 
      } 
     }); 
     updateImageStatus(); 
     backgroundThread.start(); 

    } 

    private void updateImageStatus() { 
     if (backgroundThread == null) { 
      updateTexts(); 
      return; 
     } 

     uiHandler.postDelayed(new Runnable() { 
      @Override public void run() { 
       updateImageStatus(); 
      } 
     }, 1000); 
    } 


/* 
     private void setPageBitmap(Bitmap bi) { 
      if (bi != null) 
       _bitmap = bi; 
      else { 
       _bitmap = Bitmap.createBitmap(100, 100, Config.RGB_565); 
       Canvas can = new Canvas(_bitmap); 
       can.drawColor(Color.RED); 

       Paint paint = new Paint(); 
       paint.setColor(Color.BLUE); 
       can.drawCircle(50, 50, 50, paint); 

       paint.setStrokeWidth(0); 
       paint.setColor(Color.BLACK); 
       can.drawText("Bitmap", 10, 50, paint); 
      } 
     }*/ 

     protected void updateTexts() { 
      int maxCmds = PDFPage.getParsedCommands(); 
      int curCmd = PDFPage.getLastRenderedCommand()+1; 
      if(maxCmds==curCmd){ 

        _p.dismiss(); 
        finish(); 

       Log.e("Amit","check update_finish()"); 
      }else { 
       setContent(); 
       Log.e("Amit","check update_again"); 

      } 

    } 


     private Bitmap showPage(int page, float zoom) throws Exception { 
      Bitmap b=null; 
      try { 
       Log.e("amit","Go to page bitmap"); 
       mPdfPage = mPdfFile.getPage(page, true); 
       float wi = mPdfPage.getWidth(); 
       float hei = mPdfPage.getHeight(); 


       RectF clip = null; 

       Bitmap bi = mPdfPage.getImage((int)(wi*zoom), (int)(hei*zoom), clip, true, true); 
       b=bi; 

       ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
       b.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 
       File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "Firstpdf.jpg"); 
       f.createNewFile(); 
       FileOutputStream fo = new FileOutputStream(f); 
       fo.write(bytes.toByteArray()); 
       Log.e("amit","Go to page bitmap______SAVE"); 

      } catch (Throwable e) { 
       Log.e(TAG, e.getMessage(), e); 

      } 

      return b; 
     } 

     private void parsePDF(String filename) throws PDFAuthenticationFailureException { 

      try { 
       File f = new File(filename); 
       long len = f.length(); 
       if (len == 0) { 
        Log.e("amit","No file found"); 
       } 
       else { 
        Log.e("amit","file '" + filename + "' has " + len + " bytes"); 
        openFile(f); 
       } 
      } 
      catch (PDFAuthenticationFailureException e) { 
       throw e; 
      } catch (Throwable e) { 
       e.printStackTrace(); 

      } 


     } 


     /** 
     * <p>Open a specific pdf file. Creates a DocumentInfo from the file, 
     * and opens that.</p> 
     * 
     * <p><b>Note:</b> Mapping the file locks the file until the PDFFile 
     * is closed.</p> 
     * 
     * @param file the file to open 
     * @throws IOException 
     */ 
     public void openFile(File file) throws IOException { 
      // first open the file for random access 
      RandomAccessFile raf = new RandomAccessFile(file, "r"); 

      // extract a file channel 
      FileChannel channel = raf.getChannel(); 

      // now memory-map a byte-buffer 
      ByteBuffer bb = 
        ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size())); 
      // create a PDFFile from the data 

       mPdfFile = new PDFFile(bb); 


      Log.e("Amit","Pages-----"+mPdfFile.getNumPages()); 
     } 



} 
+0

Vui lòng cho tôi biết về giấy phép đang được sử dụng bởi phần mềm này được chỉ, trong liên kết của bạn ở trên. Tôi đang tìm một cái gì đó mà là không GPL/LGPL ... Cảm ơn sự giúp đỡ của bạn – Sriram

+0

Xin chào Immy tôi đã có rất nhiều giải pháp cho PDF để hình ảnh nhưng không nhận được bất kỳ cách thích hợp. Tôi không thể tìm thấy bất kỳ thư viện miễn phí (jar) cho PDF để hình ảnh. và làm thế nào để thực hiện cái bình đó trên lớp hoạt động của tôi ...? xin vui lòng để hướng dẫn tôi ... –

+3

Điều này không hoạt động trên API dưới 21. Lỗi vẫn chưa được giải quyết. Cũng printDemo không được xác định. Bạn có thể thêm liên kết vào thư viện bạn đã sử dụng thay vì sau đó apk không? Cảm ơn –

2

Wasted vài ngày tìm kiếm thư viện PDF LGPL dành cho Android. PdfRenderer được giới thiệu ở cấp API 21 là giải pháp tốt nhất cho PDF thành hình ảnh.

Mẫu mã:

// create a new renderer 
PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor()); 

// let us just render all pages 
final int pageCount = renderer.getPageCount(); 
for (int i = 0; i < pageCount; i++) { 
    Page page = renderer.openPage(i); 

    // say we render for showing on the screen 
    page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY); 

    // do stuff with the bitmap 

    // close the page 
    page.close(); 
} 
// close the renderer 
renderer.close(); 

    private ParcelFileDescriptor getSeekableFileDescriptor() 
    { 
     ParcelFileDescriptor fd = null; 
     try 
     { 
      fd = ParcelFileDescriptor.open(new File("PATH TO YOUR PDF"), 
        ParcelFileDescriptor.MODE_READ_ONLY); 
     } 
     catch (FileNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 
     return fd; 
    } 

Hope this helps một ai đó.

+2

Mọi thứ cho API <21? – Jaydev

0

Kiểm tra thư viện này https://github.com/barteksc/AndroidPdfViewer Sau vài tuần tìm kiếm, đây là thư viện duy nhất tôi phát hiện ra rằng:

  • Hỗ trợ API Android 14 (và có thể thấp hơn, nhưng tôi đã không kiểm tra nó).
  • Sử dụng giấy phép phù hợp với nhu cầu của tôi (Giấy phép Apache 2.0).
  • Thực sự tải các tệp PDF mà không bị lỗi.
Các vấn đề liên quan