我是Android应用程序开发的新手。使用iText我已经完成了PDF创建并在该创建的文件上写入,现在我想从我的`ImageView创建图像到PDF。这是我的代码:
public class PdfCreatorActivity extends AppCompatActivity {
private static final String TAG = "PdfCreatorActivity";
private EditText mContentEditText;
private Button mCreateButton;
private File pdfFile;
final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
Intent intent;
Uri fileUri;
Button btn_choose_image;
ImageView imageView;
Bitmap bitmap, decoded;
public final int REQUEST_CAMERA = 0;
public final int SELECT_FILE = 1;
int bitmap_size = 40; // image quality 1 - 100;
int max_resolution_image = 800;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfcreator);
btn_choose_image = (Button) findViewById(R.id.btn_choose_image);
imageView = (ImageView) findViewById(R.id.image_view);
btn_choose_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
mContentEditText = (EditText) findViewById(R.id.edit_text_content);
mCreateButton = (Button) findViewById(R.id.button_create);
mCreateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mContentEditText.getText().toString().isEmpty()){
mContentEditText.setError("Body is empty");
mContentEditText.requestFocus();
return;
}
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
});
}
private void selectImage() {
imageView.setImageResource(0);
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(PdfCreatorActivity.this);
builder.setTitle("Add Photo!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
try {
Log.e("CAMERA", fileUri.getPath());
bitmap = BitmapFactory.decodeFile(fileUri.getPath());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
try {
// mengambil gambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(PdfCreatorActivity.this.getContentResolver(), data.getData());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Untuk menampilkan bitmap pada ImageView
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// Untuk resize bitmap
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DeKa");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Monitoring", "Oops! Failed create Monitoring directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_DeKa_" + timeStamp + ".jpg");
return mediaFile;
}
}
本创建PDF代码
private void createPdfWrapper() throws FileNotFoundException,DocumentException{
int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
showMessageOKCancel("You need to allow access to Storage",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
});
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
return;
}else {
createPdf();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
} else {
// Permission Denied
Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private void createPdf() throws FileNotFoundException, DocumentException {
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
pdfFile = new File(docsFolder.getAbsolutePath(),"HelloWorld.pdf");
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
document.add(new Paragraph(mContentEditText.getText().toString()));
document.close();
previewPdf();
}
private void previewPdf() {
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(pdfFile);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}else{
Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show();
}
}
我不知道如何实现图像可以使用iText生成PDF, 例子很明显......
提前感谢。
答案 0 :(得分:0)
使用PdfDocument生成pdf表单视图。
此类可以从原生Android内容生成PDF文档
示例代码:
// Create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(view.getWidth(), view.getHeight(), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw on page
view.draw(page.getCanvas());
// finish the page
document.finishPage(page);
// generate pdf
new PdfGenerationTask().execute();
使用AsyncTask
生成pdf表单document
private class PdfGenerationTask extends AsyncTask<Void, Void, File> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected File doInBackground(Void... params) {
return generatePdf();
}
@Override
protected void onPostExecute(File file) {
/* Dismiss the progress dialog after sharing */
}
}
generatePdf
方法
private File generatePdf(){
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdf"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pdf";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, pdfName);
if( document != null ){
// write the document content
try {
OutputStream out = new FileOutputStream(file);
if( out != null ){
document.writeTo(out);
// close the document
document.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
PdfDocument简单易用。 PdfDocument需要min sdk 19