我使用下面的代码并使用iText库动态创建了pdf:
try {
String str_path = Environment.getExternalStorageDirectory()
.toString();
File file;
file = new File(str_path, getString(R.string.app_name)
+ ".pdf");
FileOutputStream fos = new FileOutputStream(file);
Document document = new Document();
PdfWriter.getInstance(document, fos);
document.open();
document.add(new Paragraph("Hello World"));
document.add(new Paragraph(new Date().toString()));
document.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
比我检索976字节的pdf文件。 当我使用以下代码添加用于将图像添加到此pdf文件的代码时:
try {
String str_path = Environment.getExternalStorageDirectory()
.toString();
File file;
file = new File(str_path, getString(R.string.app_name)
+ ".pdf");
FileOutputStream fos = new FileOutputStream(file);
Document document = new Document();
PdfWriter.getInstance(document, fos);
document.open();
document.add(new Paragraph("Hello World, iText"));
document.add(new Paragraph(new Date().toString()));
Image image = Image.getInstance("ic_launcher.png");
document.add(image);
document.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
比我检索0字节的pdf文件。
我不知道什么是问题,如果您有任何相关的想法,请与我分享。感谢。
答案 0 :(得分:2)
它将解决您的问题
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
Image image = Image.getInstance(bitMapData);
答案 1 :(得分:2)
最后我将图片添加到pdf使用以下代码:
尝试{
String str_path = Environment.getExternalStorageDirectory()
.toString();
File file;
file = new File(str_path, getString(R.string.app_name)
+ ".pdf");
FileOutputStream fos = new FileOutputStream(file);
Document document = new Document();
PdfWriter.getInstance(document, fos);
InputStream ims = getAssets().open("ic_launcher.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.open();
document.add(new Paragraph("Hello World"));
document.add(new Paragraph(new Date().toString()));
document.add(image);
document.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
使用此代码,希望这对您有帮助。
答案 2 :(得分:0)
这里有一个例外,因此你检索了0字节的pdf文件