2013-12-09 149 views
-2

在应用程序的点击我已通过相机单击图像并存储在SD卡现在我想将其转换为PDF,我不知道该怎么做它。任何人都可以帮助我。 我想点击button.is它有可能将.jpg转换为pdf

+0

可能重复:http://stackoverflow.com/questions/15744454/how-to-convert-jpg-to-pdf-in-android-java – Manitoba

+0

我试图用这种方式,但未能实现它 – poojagupta

+0

问题是什么? – Manitoba

回答

4

这是一个代码,应该做的工作。我试着评论最多的行数,但如果你不明白,请告诉我。

class JpgToPdfActivity extends Activity 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.jpg_to_pdf_activity); 

     // Get button 
     Button convertButton = (Button) findViewById(R.id.convert_button); 
     convertButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick() 
      { 
       // Will run the conversion in another thread to avoid the UI to be frozen 
       Thread t = new Thread() { 
        public void run() 
        { 
         // Input file 
         String inputPath = Environment.getExternalStorageDirectory() + File.separator + "test.jpg"; 

         // Output file 
         String outputPath = Environment.getExternalStorageDirectory() + File.separator + "out.pdf"; 

         // Run conversion 
         final boolean result = JpgToPdfActivity.this.convertToPdf(inputPath, outputPath); 

         // Notify the UI 
         runOnUiThread(new Runnable() { 
          public void run() 
          { 
           if (result) Toast.makeText(JpgToPdfActivity.this, "The JPG was successfully converted to PDF.", Toast.LENGTH_SHORT).show(); 
           else Toast.makeText(JpgToPdfActivity.this, "An error occured while converting the JPG to PDF.", Toast.LENGTH_SHORT).show(); 
          } 
         }); 
        } 
       }; 
       t.start(); 
      } 
     }); 
    } 

    public static void convertToPdf(String jpgFilePath, String outputPdfPath) 
    { 
     try 
     { 
      // Check if Jpg file exists or not 
      File inputFile = new File(jpgFilePath); 
      if (!inputFile.exists()) throw new Exception("File '" + jpgFilePath + "' doesn't exist."); 

      // Create output file if needed 
      File outputFile = new File(outputPdfPath); 
      if (!outputFile.exists()) outputFile.createNewFile(); 

      Document document = new Document(); 
      PdfWriter.getInstance(document, new FileOutputStream(outputFile)); 
      document.open(); 
      Image image = Image.getInstance(jpgFilePath); 
      document.add(image);    
      document.close(); 

      return true; 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

     return false; 
    } 
} 
+0

感谢您的code.it工作!!!!!!! – poojagupta

+0

@poojagupta @poojagupta如果代码工作,那么请标记问题解决,并upvote投票人为他的努力 –

+0

@manitoba我面临的一个问题,它不是将整个图像转换为pdf,但只有一部分。可以帮我。 – poojagupta