尝试从列表视图创建 PDF
Trying to create a PDF from a listview
大家好我正在尝试通过一组图像以编程方式创建 pdf。我正在从数组列表中将图像加载到 Listview 上。单击浮动操作按钮显示图像后,我愿意创建一个新的 PDF 文件。我正在成功创建文件,不幸的是我只能在 pdf 文件中看到 5 张图像中的一张图像。出于参考目的,我在这里分享我试图实现的代码。请帮助我创建和显示 PDF 格式的图像列表
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
public class DisplayPreview extends AppCompatActivity {
String TAG = DisplayPreview.class.getName();
ListView imagesLV;
FloatingActionButton fabPDF;
TextView tv_link;
ImageView iv_image;
LinearLayout ll_pdflayout;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
boolean boolean_save;
Bitmap bitmap;
ProgressDialog progressDialog;
ArrayList<String> selectedImagesList;
String targetPdf;
DisplayPreviewAdapter displayPreviewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_preview);
Intent intent = getIntent();
selectedImagesList = intent.getStringArrayListExtra("selectedArray");
fn_permission();
imagesLV = findViewById(R.id.imagesLV);
displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList);
imagesLV.setAdapter(displayPreviewAdapter);
fabPDF = findViewById(R.id.fabPDF);
fabPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
makePDF();
} else {
}
makePDF();
}
}
});
}
private void makePDF() {
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels;
float width = displaymetrics.widthPixels;
int convertHighet = (int) hight, convertWidth = (int) width;
// Resources mResources = getResources();
// Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.img_1);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(getBitmapFromView(imagesLV), convertWidth, convertHighet, true);
// bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
// write the document content
// String targetPdf = "/sdcard/test.pdf";
targetPdf = "mnt/sdcard/testing_1.pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
boolean_save = true;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
我建议您使用 iTextPdf 轻松创建 pdf
compile 'com.itextpdf:itextg:5.5.10'
将 itextpdf
库添加到您的项目 app build.gradle
文件
implementation 'com.itextpdf:itext-pdfa:5.5.5'
下面是创建 pdf 文件并将图像添加到 table
中每个单元格的代码
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
try {
File f = new File(Environment.getExternalStorageDirectory() + "/*foldername*");
f = new File(f.getAbsolutePath() + "/" + * filename *);
if (!f.exists()) {
f.mkdir();
}
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(f.getAbsolutePath() + "/" + * filename * +".pdf"));
document.open();
for (int l = 0; l < list.size; l++) {
PdfPTable thirdPart = new PdfPTable(col);
thirdPart.getDefaultCell().setBorder(Rectangle.NO_BORDER);
thirdPart.setWidthPercentage(100.0f);
thirdPart.setHorizontalAlignment(Element.ALIGN_LEFT);
Image str = list.get(l);
PdfPCell imageCell = new PdfPCell(str);
thirdPart.addCell(imageCell);
}
document.add(thirdPart);
} catch (Exception e) {
e.printStackTrace();
}
document.close();
经过几个小时的努力,我找到了自己的答案,即使用 android 在单个 PDF 中创建多个页面,这里还有带文本注释的图像是以下源代码
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class DisplayPreview extends AppCompatActivity {
String TAG = DisplayPreview.class.getName();
ListView imagesLV;
FloatingActionButton fabPDF;
Bitmap anImage;
TextView tv_link;
ImageView iv_image;
LinearLayout ll_pdflayout;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
boolean boolean_save;
Bitmap bitmap;
ProgressDialog progressDialog;
ArrayList<String> selectedImagesList;
String targetPdf;
DisplayPreviewAdapter displayPreviewAdapter;
String familyStatus, userNameStr;
public static final Integer[] IMAGES = {
R.drawable.img_1,
R.drawable.img_2,
R.drawable.img_3,
R.drawable.img_4,
R.drawable.img_5,
R.drawable.img_6,
R.drawable.img_7
// ,R.drawable.img_8,
// R.drawable.img_9
};
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_preview);
Intent intent = getIntent();
selectedImagesList = intent.getStringArrayListExtra("selectedArray");
familyStatus = intent.getStringExtra("familyStatus");
userNameStr = intent.getStringExtra("userNameStr");
targetPdf = "mnt/sdcard/testing_2.pdf";
imagesLV = findViewById(R.id.imagesLV);
displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList, IMAGES);
// imagesLV.setAdapter(displayPreviewAdapter);
fabPDF = findViewById(R.id.fabPDF);
Drawable myDrawable = getResources().getDrawable(R.drawable.img_1);
anImage = ((BitmapDrawable) myDrawable).getBitmap();
createMultiPagePDF();
fabPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
// bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
// makePDF();
createMultiplePDF();
} else {
}
createMultiplePDF();
// makePDF();
}
}
});
}
private void createMultiPagePDF() {
pDialog = new ProgressDialog(DisplayPreview.this);
pDialog.setMessage("Please wait...Creating Invitation");
pDialog.setCancelable(false);
pDialog.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
// bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
// makePDF();
createMultiplePDF();
} else {
}
createMultiplePDF();
// makePDF();
}
}
}, 4000);
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
public void createMultiplePDF() {
// targetPdf = "mnt/sdcard/testing_1.pdf";
targetPdf = "mnt/sdcard/" + userNameStr + ".pdf";
File filePath = new File(targetPdf);
// Document document = new Document();
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
// step 2
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// step 3
document.open();
// step 4
try {
Drawable myDrawable = null;
for (int i = 0; i < selectedImagesList.size(); i++) {
//
String imagePath = selectedImagesList.get(i).replaceAll("^\"|\"$", "");
Log.i(TAG, "Image Path is :: 271 :: " + imagePath);
// if (imagePath.equals("R.drawable.img_8")) {
if (imagePath.equals(userNameStr)) {
Bitmap processedBitmap = ProcessingBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_2")) {
myDrawable = getResources().getDrawable(R.drawable.img_2);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_3")) {
myDrawable = getResources().getDrawable(R.drawable.img_3);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_4")) {
myDrawable = getResources().getDrawable(R.drawable.img_4);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_5")) {
myDrawable = getResources().getDrawable(R.drawable.img_5);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_6")) {
myDrawable = getResources().getDrawable(R.drawable.img_6);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_7")) {
myDrawable = getResources().getDrawable(R.drawable.img_7);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
/* if (imagePath.equals("R.drawable.img_8")) {
myDrawable = getResources().getDrawable(R.drawable.img_8);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
} if (imagePath.equals("R.drawable.img_9")) {
myDrawable = getResources().getDrawable(R.drawable.img_9);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}*/
}
document.close();
pDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
finish();
} catch (DocumentException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressLint("ResourceAsColor")
private Bitmap ProcessingBitmap() {
Resources resources = DisplayPreview.this.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.img_1);
Bitmap.Config config = bm1.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
// newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
anImage = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
// Canvas newCanvas = new Canvas(newBitmap);
Canvas newCanvas = new Canvas(anImage);
newCanvas.drawBitmap(bm1, 0, 0, null);
String captionString = userNameStr.trim();
if (captionString != null) {
TextPaint paintText = new TextPaint(Paint.ANTI_ALIAS_FLAG);
paintText.setColor(R.color.wedding_guest_name);
paintText.setTextSize(100);
paintText.setStyle(Paint.Style.FILL_AND_STROKE);
paintText.setTextAlign(Paint.Align.CENTER);
int textWidth = newCanvas.getWidth() - (int) (250 * scale);
StaticLayout textLayout = new StaticLayout(
captionString, paintText, textWidth, Layout.Alignment.ALIGN_LEFT, 1.0f, 1.4f, false);
Rect rectText = new Rect();
paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
float xPos = (newCanvas.getWidth() / 2.16f);
float yPos = (int) ((newCanvas.getHeight() / 2.4) - ((paintText.descent() + paintText.ascent()) / 3.0));
float x = newCanvas.getWidth()/2;
// float y = newCanvas.getHeight()/2;
// draw text to the Canvas center
newCanvas.save();
// newCanvas.translate(xPos, yPos);
newCanvas.translate(x, yPos);
textLayout.draw(newCanvas);
newCanvas.restore();
// drawMultiLineText(captionString,xPos, yPos, paintText, newCanvas);
// newCanvas.drawText(captionString,xPos, yPos, paintText);
} else {
Toast.makeText(getApplicationContext(),
"caption empty!",
Toast.LENGTH_LONG).show();
}
// return newBitmap;
return anImage;
}
}
大家好我正在尝试通过一组图像以编程方式创建 pdf。我正在从数组列表中将图像加载到 Listview 上。单击浮动操作按钮显示图像后,我愿意创建一个新的 PDF 文件。我正在成功创建文件,不幸的是我只能在 pdf 文件中看到 5 张图像中的一张图像。出于参考目的,我在这里分享我试图实现的代码。请帮助我创建和显示 PDF 格式的图像列表
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
public class DisplayPreview extends AppCompatActivity {
String TAG = DisplayPreview.class.getName();
ListView imagesLV;
FloatingActionButton fabPDF;
TextView tv_link;
ImageView iv_image;
LinearLayout ll_pdflayout;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
boolean boolean_save;
Bitmap bitmap;
ProgressDialog progressDialog;
ArrayList<String> selectedImagesList;
String targetPdf;
DisplayPreviewAdapter displayPreviewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_preview);
Intent intent = getIntent();
selectedImagesList = intent.getStringArrayListExtra("selectedArray");
fn_permission();
imagesLV = findViewById(R.id.imagesLV);
displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList);
imagesLV.setAdapter(displayPreviewAdapter);
fabPDF = findViewById(R.id.fabPDF);
fabPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
makePDF();
} else {
}
makePDF();
}
}
});
}
private void makePDF() {
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels;
float width = displaymetrics.widthPixels;
int convertHighet = (int) hight, convertWidth = (int) width;
// Resources mResources = getResources();
// Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.img_1);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(getBitmapFromView(imagesLV), convertWidth, convertHighet, true);
// bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
// write the document content
// String targetPdf = "/sdcard/test.pdf";
targetPdf = "mnt/sdcard/testing_1.pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
boolean_save = true;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
if ((ActivityCompat.shouldShowRequestPermissionRationale(DisplayPreview.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(DisplayPreview.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
我建议您使用 iTextPdf 轻松创建 pdf
compile 'com.itextpdf:itextg:5.5.10'
将 itextpdf
库添加到您的项目 app build.gradle
文件
implementation 'com.itextpdf:itext-pdfa:5.5.5'
下面是创建 pdf 文件并将图像添加到 table
中每个单元格的代码Document document = new Document(PageSize.A4, 10, 10, 10, 10);
try {
File f = new File(Environment.getExternalStorageDirectory() + "/*foldername*");
f = new File(f.getAbsolutePath() + "/" + * filename *);
if (!f.exists()) {
f.mkdir();
}
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(f.getAbsolutePath() + "/" + * filename * +".pdf"));
document.open();
for (int l = 0; l < list.size; l++) {
PdfPTable thirdPart = new PdfPTable(col);
thirdPart.getDefaultCell().setBorder(Rectangle.NO_BORDER);
thirdPart.setWidthPercentage(100.0f);
thirdPart.setHorizontalAlignment(Element.ALIGN_LEFT);
Image str = list.get(l);
PdfPCell imageCell = new PdfPCell(str);
thirdPart.addCell(imageCell);
}
document.add(thirdPart);
} catch (Exception e) {
e.printStackTrace();
}
document.close();
经过几个小时的努力,我找到了自己的答案,即使用 android 在单个 PDF 中创建多个页面,这里还有带文本注释的图像是以下源代码
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class DisplayPreview extends AppCompatActivity {
String TAG = DisplayPreview.class.getName();
ListView imagesLV;
FloatingActionButton fabPDF;
Bitmap anImage;
TextView tv_link;
ImageView iv_image;
LinearLayout ll_pdflayout;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
boolean boolean_save;
Bitmap bitmap;
ProgressDialog progressDialog;
ArrayList<String> selectedImagesList;
String targetPdf;
DisplayPreviewAdapter displayPreviewAdapter;
String familyStatus, userNameStr;
public static final Integer[] IMAGES = {
R.drawable.img_1,
R.drawable.img_2,
R.drawable.img_3,
R.drawable.img_4,
R.drawable.img_5,
R.drawable.img_6,
R.drawable.img_7
// ,R.drawable.img_8,
// R.drawable.img_9
};
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_preview);
Intent intent = getIntent();
selectedImagesList = intent.getStringArrayListExtra("selectedArray");
familyStatus = intent.getStringExtra("familyStatus");
userNameStr = intent.getStringExtra("userNameStr");
targetPdf = "mnt/sdcard/testing_2.pdf";
imagesLV = findViewById(R.id.imagesLV);
displayPreviewAdapter = new DisplayPreviewAdapter(this, selectedImagesList, IMAGES);
// imagesLV.setAdapter(displayPreviewAdapter);
fabPDF = findViewById(R.id.fabPDF);
Drawable myDrawable = getResources().getDrawable(R.drawable.img_1);
anImage = ((BitmapDrawable) myDrawable).getBitmap();
createMultiPagePDF();
fabPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
// bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
// makePDF();
createMultiplePDF();
} else {
}
createMultiplePDF();
// makePDF();
}
}
});
}
private void createMultiPagePDF() {
pDialog = new ProgressDialog(DisplayPreview.this);
pDialog.setMessage("Please wait...Creating Invitation");
pDialog.setCancelable(false);
pDialog.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (boolean_save) {
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
} else {
if (boolean_permission) {
progressDialog = new ProgressDialog(DisplayPreview.this);
progressDialog.setMessage("Please wait");
// bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
bitmap = loadBitmapFromView(imagesLV, imagesLV.getWidth(), imagesLV.getHeight());
// makePDF();
createMultiplePDF();
} else {
}
createMultiplePDF();
// makePDF();
}
}
}, 4000);
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
public void createMultiplePDF() {
// targetPdf = "mnt/sdcard/testing_1.pdf";
targetPdf = "mnt/sdcard/" + userNameStr + ".pdf";
File filePath = new File(targetPdf);
// Document document = new Document();
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
// step 2
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// step 3
document.open();
// step 4
try {
Drawable myDrawable = null;
for (int i = 0; i < selectedImagesList.size(); i++) {
//
String imagePath = selectedImagesList.get(i).replaceAll("^\"|\"$", "");
Log.i(TAG, "Image Path is :: 271 :: " + imagePath);
// if (imagePath.equals("R.drawable.img_8")) {
if (imagePath.equals(userNameStr)) {
Bitmap processedBitmap = ProcessingBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_2")) {
myDrawable = getResources().getDrawable(R.drawable.img_2);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_3")) {
myDrawable = getResources().getDrawable(R.drawable.img_3);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_4")) {
myDrawable = getResources().getDrawable(R.drawable.img_4);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_5")) {
myDrawable = getResources().getDrawable(R.drawable.img_5);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_6")) {
myDrawable = getResources().getDrawable(R.drawable.img_6);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
if (imagePath.equals("R.drawable.img_7")) {
myDrawable = getResources().getDrawable(R.drawable.img_7);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}
/* if (imagePath.equals("R.drawable.img_8")) {
myDrawable = getResources().getDrawable(R.drawable.img_8);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
} if (imagePath.equals("R.drawable.img_9")) {
myDrawable = getResources().getDrawable(R.drawable.img_9);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.JPEG, 40, stream);
Image myImg = Image.getInstance(stream.toByteArray());
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = (float) ((displaymetrics.heightPixels / 2) * (1.1));
float width = (float) ((displaymetrics.widthPixels / 2) * (1.6));
// myImg.scaleToFit(hight, width);
myImg.scaleToFit(PageSize.ARCH_A);
myImg.setAlignment(Image.ALIGN_CENTER);
document.add(myImg);
writer.setPageEmpty(false);
}*/
}
document.close();
pDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
intent.putExtra("pdfFile", targetPdf);
startActivity(intent);
finish();
} catch (DocumentException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressLint("ResourceAsColor")
private Bitmap ProcessingBitmap() {
Resources resources = DisplayPreview.this.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.img_1);
Bitmap.Config config = bm1.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
// newBitmap = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
anImage = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), config);
// Canvas newCanvas = new Canvas(newBitmap);
Canvas newCanvas = new Canvas(anImage);
newCanvas.drawBitmap(bm1, 0, 0, null);
String captionString = userNameStr.trim();
if (captionString != null) {
TextPaint paintText = new TextPaint(Paint.ANTI_ALIAS_FLAG);
paintText.setColor(R.color.wedding_guest_name);
paintText.setTextSize(100);
paintText.setStyle(Paint.Style.FILL_AND_STROKE);
paintText.setTextAlign(Paint.Align.CENTER);
int textWidth = newCanvas.getWidth() - (int) (250 * scale);
StaticLayout textLayout = new StaticLayout(
captionString, paintText, textWidth, Layout.Alignment.ALIGN_LEFT, 1.0f, 1.4f, false);
Rect rectText = new Rect();
paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
float xPos = (newCanvas.getWidth() / 2.16f);
float yPos = (int) ((newCanvas.getHeight() / 2.4) - ((paintText.descent() + paintText.ascent()) / 3.0));
float x = newCanvas.getWidth()/2;
// float y = newCanvas.getHeight()/2;
// draw text to the Canvas center
newCanvas.save();
// newCanvas.translate(xPos, yPos);
newCanvas.translate(x, yPos);
textLayout.draw(newCanvas);
newCanvas.restore();
// drawMultiLineText(captionString,xPos, yPos, paintText, newCanvas);
// newCanvas.drawText(captionString,xPos, yPos, paintText);
} else {
Toast.makeText(getApplicationContext(),
"caption empty!",
Toast.LENGTH_LONG).show();
}
// return newBitmap;
return anImage;
}
}