点击应用程序我通过相机点击了图像并存储在SD卡现在我想将其转换为pdf,我不知道该怎么做。任何人都可以帮助我。 我想点击一个按钮来实现它。可能
答案 0 :(得分:5)
这是一个应该完成这项工作的代码。我试图评论最大线数,但如果你不明白,请告诉我。
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;
}
}