Android : 如何在 iText 生成的 PDF 中将 url 图像添加到我的 header
Android : how to add an url image to my header in iText generated PDF
我正在使用 iText 生成 PDF.Pdf 是为了显示学校中的一些记录而生成的,所以我需要在顶部的中心显示学校标志和学校名称 header第一页的。我有图像文件的字符串 HTTP URL,它可以是任何大小。我想在不损失质量的情况下调整图像大小,并在 header 部分进行调整(这样才有意义),并且需要在下方显示学校名称。我的问题是我不知道如何添加图像,所以它显示在“header 框中”。
这里有一些代码片段...
private void createPdf() {
try {
String imgURL = "http URL";
String schoolName = "School Name";
File filePath = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS), "PROJECT");
if (! filePath.exists()){
if (! filePath.mkdirs()){
}else{
}
}
// Create a file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
fileExp = new File(filePath+"/Report_"+ timeStamp + ".pdf");
photoURI = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".fileprovider", fileExp);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileExp));
document.open();
addMetaData(document);
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
Paragraph para1 = new Paragraph(repHeader, catFont);
para1.setAlignment(Element.ALIGN_CENTER);
preface.add(para1);
addEmptyLine(preface, 2);
Paragraph para3 = new Paragraph("Period : ", textBold);
Chunk perChunk3 = new Chunk("from "+edtFromDate.getText().toString()+" to "+edtToDate.getText().toString(),textNormal);
para3.add(perChunk3);
preface.add(para3);
addEmptyLine(preface, 1);
document.close();
//insertDocument("Report_"+ timeStamp + ".pdf");
Intent emailIn = new Intent(Intent.ACTION_SEND);
emailIn.setType("application/pdf");
emailIn.putExtra(Intent.EXTRA_STREAM, photoURI);
emailIn.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIn.putExtra(Intent.EXTRA_EMAIL, new String[] { selEmailId });
emailIn.putExtra(Intent.EXTRA_SUBJECT, "Report : "+repHeader);
emailIn.putExtra(Intent.EXTRA_TEXT, repHeader);
startActivityForResult(Intent.createChooser(emailIn, "E-mail"),15);
} catch (Exception e) {
e.printStackTrace();
}
}
下面是依赖关系:
implementation 'com.itextpdf:itextg:5.5.10'
我会按照此处的说明进行操作 https://memorynotfound.com/adding-header-footer-pdf-using-itext-java/ 并自定义他们的代码以适应。
为了在此处保留答案,最基本的是您需要在 document.close()
之前创建一个“addHeader”方法
使用类似于此代码块的内容
private void addHeader(PdfWriter writer){
PdfPTable header = new PdfPTable(2);
try {
// set defaults
header.setWidths(new int[]{2, 24});
header.setTotalWidth(527);
header.setLockedWidth(true);
header.getDefaultCell().setFixedHeight(40);
header.getDefaultCell().setBorder(Rectangle.BOTTOM);
header.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// add image
Image logo = Image.getInstance(HeaderFooterPageEvent.class.getResource("/memorynotfound-logo.jpg"));
header.addCell(logo);
// add text
PdfPCell text = new PdfPCell();
text.setPaddingBottom(15);
text.setPaddingLeft(10);
text.setBorder(Rectangle.BOTTOM);
text.setBorderColor(BaseColor.LIGHT_GRAY);
text.addElement(new Phrase("iText PDF Header Footer Example", new Font(Font.FontFamily.HELVETICA, 12)));
text.addElement(new Phrase("https://memorynotfound.com", new Font(Font.FontFamily.HELVETICA, 8)));
header.addCell(text);
// write content
header.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
} catch(DocumentException de) {
throw new ExceptionConverter(de);
} catch (MalformedURLException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
您可以将图像添加到文档并使用以下代码按首选高度或宽度缩放为图像
这里我根据preferredImageHeight
缩放了图片的宽度
Image image = Image.getInstance("https://static.wikia.nocookie.net/rickandmorty/images/9/95/HarryherpsonHS.jpg/revision/latest/top-crop/width/360/height/360?cb=20150908094923");
image.setAlignment(Element.ALIGN_CENTER);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
float preferredImageHeight = 60;
float widthScale = image.getScaledHeight() / preferredImageHeight;
image.scaleAbsolute(image.getScaledWidth() / widthScale, preferredImageHeight);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
document.add(image);
我正在使用 iText 生成 PDF.Pdf 是为了显示学校中的一些记录而生成的,所以我需要在顶部的中心显示学校标志和学校名称 header第一页的。我有图像文件的字符串 HTTP URL,它可以是任何大小。我想在不损失质量的情况下调整图像大小,并在 header 部分进行调整(这样才有意义),并且需要在下方显示学校名称。我的问题是我不知道如何添加图像,所以它显示在“header 框中”。
这里有一些代码片段...
private void createPdf() {
try {
String imgURL = "http URL";
String schoolName = "School Name";
File filePath = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS), "PROJECT");
if (! filePath.exists()){
if (! filePath.mkdirs()){
}else{
}
}
// Create a file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
fileExp = new File(filePath+"/Report_"+ timeStamp + ".pdf");
photoURI = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".fileprovider", fileExp);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileExp));
document.open();
addMetaData(document);
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
Paragraph para1 = new Paragraph(repHeader, catFont);
para1.setAlignment(Element.ALIGN_CENTER);
preface.add(para1);
addEmptyLine(preface, 2);
Paragraph para3 = new Paragraph("Period : ", textBold);
Chunk perChunk3 = new Chunk("from "+edtFromDate.getText().toString()+" to "+edtToDate.getText().toString(),textNormal);
para3.add(perChunk3);
preface.add(para3);
addEmptyLine(preface, 1);
document.close();
//insertDocument("Report_"+ timeStamp + ".pdf");
Intent emailIn = new Intent(Intent.ACTION_SEND);
emailIn.setType("application/pdf");
emailIn.putExtra(Intent.EXTRA_STREAM, photoURI);
emailIn.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIn.putExtra(Intent.EXTRA_EMAIL, new String[] { selEmailId });
emailIn.putExtra(Intent.EXTRA_SUBJECT, "Report : "+repHeader);
emailIn.putExtra(Intent.EXTRA_TEXT, repHeader);
startActivityForResult(Intent.createChooser(emailIn, "E-mail"),15);
} catch (Exception e) {
e.printStackTrace();
}
}
下面是依赖关系:
implementation 'com.itextpdf:itextg:5.5.10'
我会按照此处的说明进行操作 https://memorynotfound.com/adding-header-footer-pdf-using-itext-java/ 并自定义他们的代码以适应。
为了在此处保留答案,最基本的是您需要在 document.close()
之前创建一个“addHeader”方法使用类似于此代码块的内容
private void addHeader(PdfWriter writer){
PdfPTable header = new PdfPTable(2);
try {
// set defaults
header.setWidths(new int[]{2, 24});
header.setTotalWidth(527);
header.setLockedWidth(true);
header.getDefaultCell().setFixedHeight(40);
header.getDefaultCell().setBorder(Rectangle.BOTTOM);
header.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// add image
Image logo = Image.getInstance(HeaderFooterPageEvent.class.getResource("/memorynotfound-logo.jpg"));
header.addCell(logo);
// add text
PdfPCell text = new PdfPCell();
text.setPaddingBottom(15);
text.setPaddingLeft(10);
text.setBorder(Rectangle.BOTTOM);
text.setBorderColor(BaseColor.LIGHT_GRAY);
text.addElement(new Phrase("iText PDF Header Footer Example", new Font(Font.FontFamily.HELVETICA, 12)));
text.addElement(new Phrase("https://memorynotfound.com", new Font(Font.FontFamily.HELVETICA, 8)));
header.addCell(text);
// write content
header.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
} catch(DocumentException de) {
throw new ExceptionConverter(de);
} catch (MalformedURLException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
您可以将图像添加到文档并使用以下代码按首选高度或宽度缩放为图像
这里我根据preferredImageHeight
Image image = Image.getInstance("https://static.wikia.nocookie.net/rickandmorty/images/9/95/HarryherpsonHS.jpg/revision/latest/top-crop/width/360/height/360?cb=20150908094923");
image.setAlignment(Element.ALIGN_CENTER);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
float preferredImageHeight = 60;
float widthScale = image.getScaledHeight() / preferredImageHeight;
image.scaleAbsolute(image.getScaledWidth() / widthScale, preferredImageHeight);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
document.add(image);