简体   繁体   English

如何在Java中的iext中调整图像大小

[英]How to resize image in itext in java

This is my source code. 这是我的源代码。

  Document document = new Document();
    String txtVehNo = "";
    String fDate = "", tDate = "", remtype = "0";
    String fileName = "Reminders_" + Utility.sysDate("yyyy_MM_dd") + ".pdf";
    String asDate = Utility.sysDate("dd/MM/yyyy");
    ArrayList<ReminderPDF> reminderPDFs = null;
    UserDetails userDetails = null;
    String txtMarNo = "";
    String formattedDate = "";
    String address = "";



    Blob imageBlob = null;
    byte[] imageBytes = new byte[0];

    try {
        txtVehNo = request.getParameter("txtVehNo2");
        fDate = request.getParameter("txtDate3");
        tDate = request.getParameter("txtDate4");
        remtype = request.getParameter("remtype");
        txtMarNo = request.getParameter("txtMarNo");

        if (txtVehNo != null && txtVehNo != "") {

            reminderPDFs = DataManagerBean.downloadRemindersForRequirementLetter(txtVehNo, remtype);


        } else if (txtMarNo != null && txtMarNo != "") {

            reminderPDFs = DataManagerBean.downloadRemindersForRequirementLetterByMarNo(txtMarNo, remtype);


        } else {

            reminderPDFs = DataManagerBean.downloadRemindersForRequirementLetter(fDate, tDate, remtype);


        }
        if (reminderPDFs.size() > 0) {

            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
            PdfWriter.getInstance(document, response.getOutputStream());
            //PdfWriter.getInstance(document, new FileOutputStream(fileName));
            document.open();
            document.setPageSize(PageSize.A4);
            document.setMargins(85, 85, 85, 85);
            for (int i = 0; i < reminderPDFs.size(); i++) {
                String adrstr[] = reminderPDFs.get(i).address.split("\r\n");

                address = reminderPDFs.get(i).address.replaceAll(adrstr[adrstr.length - 1], "");
                document.newPage();
                Paragraph[] paragraph = new Paragraph[8];
                paragraph[0] = new Paragraph(new Phrase(reminderPDFs.get(i).mainHeader, FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD)));
                paragraph[0].setAlignment(Element.ALIGN_RIGHT);
                document.add(paragraph[0]);
                paragraph[1] = new Paragraph(new Phrase(reminderPDFs.get(i).subHeader, FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph[1].setAlignment(Element.ALIGN_RIGHT);
                document.add(paragraph[1]);
                if (reminderPDFs.get(i).print.equals("Y")) {
                    paragraph[2] = new Paragraph(new Phrase("(Reprint)", FontFactory.getFont(FontFactory.COURIER, 10)));
                } else {
                    paragraph[2] = new Paragraph(new Phrase("", FontFactory.getFont(FontFactory.COURIER, 11)));
                }
                paragraph[2].setAlignment(Element.ALIGN_RIGHT);
                document.add(paragraph[2]);
                paragraph[3] = new Paragraph(new Phrase("Date : " + reminderPDFs.get(i).asDate, FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph[3].setAlignment(Element.ALIGN_RIGHT);
                document.add(paragraph[3]);
                paragraph[4] = new Paragraph(new Phrase(" ", FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD)));
                paragraph[4].setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph[4]);
                paragraph[5] = new Paragraph(new Phrase(address, FontFactory.getFont(FontFactory.COURIER, 11, Font.BOLD)));
                paragraph[5].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph[5]);
                paragraph[6] = new Paragraph(new Phrase("\n" + adrstr[adrstr.length - 1], FontFactory.getFont(FontFactory.COURIER, 11, Font.PLAIN)));
                paragraph[6].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph[6]);
                paragraph[7] = new Paragraph(new Phrase(" ", FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD)));
                paragraph[7].setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph[7]);

                PdfPTable table = new PdfPTable(2);
                table.setWidthPercentage(100);


                formattedDate = Utility.dateFormatter(reminderPDFs.get(i).dol, "yyyy-MM-dd", "dd-MM-yyyy");

                table.addCell(new Phrase("Vehicle No: " + reminderPDFs.get(i).vehno, FontFactory.getFont(FontFactory.COURIER, 11)));
                table.addCell(new Phrase("MAR No       : " + reminderPDFs.get(i).marno, FontFactory.getFont(FontFactory.COURIER, 11)));
                table.addCell(new Phrase("Policy No : " + reminderPDFs.get(i).policyno, FontFactory.getFont(FontFactory.COURIER, 11)));
                table.addCell(new Phrase("Date of Loss : " + formattedDate, FontFactory.getFont(FontFactory.COURIER, 11)));
                document.add(table);

                Paragraph[] paragraph2 = new Paragraph[3];
                paragraph2[0] = new Paragraph(new Phrase(" ", FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD)));
                paragraph2[0].setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph2[0]);

                String[] docs = reminderPDFs.get(i).content.split("\r\n");

                paragraph2[1] = new Paragraph(new Phrase(docs[0], FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph2[1].setAlignment(Element.ALIGN_JUSTIFIED);
                document.add(paragraph2[1]);
                paragraph2[2] = new Paragraph(new Phrase(" ", FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD)));
                paragraph2[2].setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph2[2]);


                // if (reminderPDFs.get(i).docs.length() > 0) {
                int k = 1;
                for (int j = 1; j < docs.length; j++) {
                    if (!docs[j].trim().equalsIgnoreCase("")) {
                        document.add(new Paragraph(new Phrase("          " + k + ". " + docs[j].trim(), FontFactory.getFont(FontFactory.COURIER, 11))));
                        k++;
                    }
                }
                // }

                Paragraph[] paragraph3 = new Paragraph[7];
                paragraph3[0] = new Paragraph(new Phrase(" ", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD)));
                paragraph3[0].setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph3[0]);

                paragraph3[1] = new Paragraph(new Phrase("Thank You,", FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph3[1].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph3[1]);

                paragraph3[2] = new Paragraph(new Phrase("Yours Faithfully,", FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph3[2].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph3[2]);

                paragraph3[3] = new Paragraph(new Phrase("Union Assurance General Ltd", FontFactory.getFont(FontFactory.COURIER, 11, Font.BOLD)));
                paragraph3[3].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph3[3]);

                paragraph3[4] = new Paragraph(new Phrase(" ", FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD)));
                paragraph3[4].setAlignment(Element.ALIGN_CENTER);
                document.add(paragraph3[4]);


                imageBlob = DataManagerBean.getESignature(reminderPDFs.get(i).createdUser);
                if (imageBlob != null) {
                    imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());
                    Image img = Image.getInstance(imageBytes);
                    float width = img.getWidth();
                    float hight = img.getHeight();
                    if (width > 200 || hight > 100) {
//                        img.scaleAbsoluteWidth(200);
//                        img.scaleAbsoluteHeight(100);
 //                       img.scaleAbsolute(200f, 100f);
                        img.scaleToFit(200f, 100f);
                    }
                    width = img.getScaledWidth();
                    hight = img.getScaledHeight();
                    document.add(img);
                }

                userDetails = UserBean.getUserDetailsByUserId(reminderPDFs.get(i).createdUser);

                paragraph3[5] = new Paragraph(new Phrase((userDetails.getuFName().concat(" ")).concat(userDetails.getuLName()), FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph3[5].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph3[5]);


                paragraph3[6] = new Paragraph(new Phrase(userDetails.getDesig(), FontFactory.getFont(FontFactory.COURIER, 11)));
                paragraph3[6].setAlignment(Element.ALIGN_LEFT);
                document.add(paragraph3[6]);


                //DataManagerBean.printStatusUpdate(reminderPDFs.get(i).rmid, "Y");
            }
            document.close();

            response.sendRedirect("Reminders.jsp");

        } else {
            if (txtVehNo != null && txtVehNo != "") {
                response.sendRedirect("Reminders.jsp?msgtype=3&msg=No Records for Policy/Vehicle No. - " + txtVehNo);
            } else if (txtMarNo != null && txtMarNo != "") {
                response.sendRedirect("Reminders.jsp?msgtype=4&msg=No Records for Mar No. - " + txtMarNo);
            } else if (fDate != null && fDate != "") {
                response.sendRedirect("Reminders.jsp?msgtype=5&msg=No Records between " + fDate + " to " + tDate);
            }
        }
    } catch (DocumentException e) {
        SystemMessage.getInstance().writeMessage("ERROR : DownloadRequirements.jsp - " + e.toString());
    } finally {
        try {
            //reminderPDFs = null;
        } catch (Exception ex) {
        }
    }

I tried 我试过了
img.scaleAbsoluteWidth(200); img.scaleAbsoluteWidth(200);
img.scaleAbsoluteHeight(100); img.scaleAbsoluteHeight(100);
img.scaleAbsolute(200f, 100f); img.scaleAbsolute(200f,100f);
img.scaleToFit(200f, 100f); img.scaleToFit(200f,100f);
But non of this resizing the image. 但是,这并不能调整图像的大小。
When I debug the code I get width=200 and height= 100 for value too. 当我调试代码时,我也得到width = 200和height = 100作为值。 I guess that means it's height and width changed. 我想这意味着它的高度和宽度都改变了。
Please let me know what is the issue in here. 请让我知道这里的问题是什么。
THANK YOU. 谢谢。

Note Later 稍后注意
Issues wasn't any of these methods. 问题不是这些方法中的任何一个。 Issue was image not compatible with that size. 问题是图像与该尺寸不兼容。 After I set size to 100,50 imaged resized perfectly. 在我将大小设置为100,50之后,图像大小会完美调整。
Thank you again. 再次感谢你。

Your allegation "none of this is resizing the image" is wrong, and you are using the wrong methods to get the width and height of the image. 您的指控“所有这些都不是调整图像的大小”是错误的,并且您使用了错误的方法来获取图像的宽度和高度。 Take a look at chapter 2 of my book : 看一看我的书的第二章

There are different ways to change the dimensions of an image: 有多种更改图像尺寸的方法:

  • The width and height parameters of scaleToFit() define the maximum dimensions of the image. scaleToFit()的width和height参数定义图像的最大尺寸。 If the width/height ratio differs from the aspect ratio of the image, either the width, or the height, will be smaller than the corresponding parameter of this method. 如果宽高比与图像的高宽比不同,则宽度或高度将小于此方法的相应参数。
  • The width and height parameters will be respected when using scaleAbsolute() . 使用scaleAbsolute()时,将遵守width和height参数。 The resulting image risks being stretched in the X or Y direction if you don't choose the parameters wisely. 如果您不明智地选择参数,则产生的图像可能会沿X或Y方向拉伸。 You can also use scaleAbsoluteWidth() and scaleAbsoluteHeight() . 您还可以使用scaleAbsoluteWidth()scaleAbsoluteHeight()
  • scalePercent() comes in two versions: one with two parameters, a percentage for the width and a percentage for the height; scalePercent()有两个版本:一个带有两个参数,一个用于宽度百分比,一个用于高度百分比; and another with only one parameter, a percentage that will be applied equally to the width and the height. 另一个只有一个参数,一个百分比将相等地应用于宽度和高度。

It's a common misconception that resizing images in iText also changes the quality of the image. 常见的误解是,在iText中调整图像大小还会改变图像的质量。 It's important to understand that iText takes the image as is: iText doesn't change the number of pixels in the image. 重要的是要了解iText照原样拍摄图像:iText不会更改图像中的像素数。

There are many examples that prove that these methods effectively change the size of the image in the document. 有许多示例证明这些方法有效地更改了文档中图像的大小。

If you continue reading the documentation, you discover another problem in your code: 如果继续阅读文档,则会在代码中发现另一个问题:

When creating an Image instance from a file, you won't always know its dimensions before or even after scaling it. 从文件创建Image实例时,在缩放之前或什至在缩放之后,您并不总是知道其尺寸。 You can get the width and height of the image with these methods: 您可以使用以下方法获取图像的宽度和高度:

  • getWidth() and getHeight() are inherited from the Rectangle object. getWidth()getHeight()Rectangle对象继承。 They return the original height and width of the image. 它们返回图像的原始高度和宽度。
  • getPlainWidth() and getPlainHeight() return the width and height after scaling. getPlainWidth()getPlainHeight()返回缩放后的宽度和高度。 These are the dimensions of the image used to print it on a page. 这些是用于在页面上打印图像的尺寸。
  • getScaledWidth() and getScaledHeight() return the width and height needed to print the image. getScaledWidth()getScaledHeight()返回打印图像所需的宽度和高度。 These dimensions are equal to the plain width and height, except in cases where the image is rotated. 这些尺寸等于普通宽度和高度,除非旋转图像。

In your code, you get the original dimensions of the image. 在代码中,您将获得图像的原始尺寸。 You change the dimensions of the image, and then you ask for the original dimensions. 更改图像的尺寸,然后要求原始尺寸。 It shouldn't surprise you that you don't get different dimensions when asking for the original dimensions instead of the original dimensions. 要求原始尺寸而不是原始尺寸时,您不会得到不同的尺寸,这不足为奇。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM