【问题标题】:Android : how to add an url image to my header in iText generated PDFAndroid:如何在 iText 生成的 PDF 中将 url 图像添加到我的标题中
【发布时间】:2021-08-20 18:09:44
【问题描述】:

我正在使用 iText 生成 PDF。生成 PDF 是为了显示学校的一些记录,所以我需要在第一页顶部标题的中心显示学校标志和学校名称。我有可能是任何大小的图像文件的字符串 HTTP URL。我想在不损失质量的情况下调整图像大小并在标题部分进行调整(因此有意义),并且需要在下面显示学校名称。我的问题是我不知道如何添加图像,所以它显示在“标题框”中。

这里有一些代码sn-ps ...

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'

【问题讨论】:

    标签: android pdf itext pdf-generation


    【解决方案1】:

    您可以使用以下代码将图像添加到文档并按首选高度或宽度缩放图像

    这里我已经根据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);
    

    【讨论】:

      【解决方案2】:

      我会按照这里的说明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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-13
        • 1970-01-01
        • 1970-01-01
        • 2015-04-11
        相关资源
        最近更新 更多