为什么在使用Android中的iText库将图像转换为PDF时图像会被裁剪

shi*_*ani 7 pdf android itext

在我的应用程序中,我想将用户选择的图像转换为一个PDF文件.我正在使用许多人建议的iText库.用户选择多个图像,并使用它创建一个pdf,其中每个图像是1 pdf页面.

我使用的代码如下

    Document document = new Document(PageSize.A4);
            try {

                String path = Environment.getExternalStorageDirectory()+"/PDFile.pdf";

                File file= new File(path);

                if(file.exists())
                {

                }
                else
                {
                    file.createNewFile();
                }


                PdfWriter.getInstance(document,new FileOutputStream(path));

                document.open();

                for(int i =0; i<pdfImage.size();i++)
                {
                    Image image = Image.getInstance(pdfImage.get(i));
                    image.scaleAbsolute(PageSize.A4);
                    image.setAbsolutePosition(0, 0);
                    document.add(image);

                }

                document.close();



            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
Run Code Online (Sandbox Code Playgroud)

生成pdf但是图像被裁剪.只有一半的图像是可见的,其余部分被裁剪.

我是否必须为PDF格式设置采用图像大小?

或者我是否必须更改或调整图像大小以采用pdf页面大小?

请帮忙!!我不知道怎么解决这个???

Bru*_*gie 12

当你这样做:

Document document = new Document();
Run Code Online (Sandbox Code Playgroud)

然后,您隐式创建一个文档,其页面的页面大小称为A4.即:宽度为595,高度为842个用户单位.

如果添加较小的图像,则不会裁剪它们.如果添加更大的图像.图像将被裁剪......

如果您希望图像完全适合页面,您有两种选择:

  1. 调整页面的大小,或
  2. 调整图像的大小.

两个选项都是等效的,因为iText不会改变图像的分辨率:每个像素都会被保留.

选项1:

请参阅我对问题的回答:在iText Java上添加地图

在这个问题中,我这样做:

Image img = Image.getInstance(IMG);
Document document = new Document(img);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
img.setAbsolutePosition(0, 0);
document.add(img);
document.close();
Run Code Online (Sandbox Code Playgroud)

Document对象接受Rectangleas参数.这Rectangle以用户单位定义页面大小.由于Image类是类的子Rectangle类,我可以使用Image实例作为参数来创建Document实例.

另一种选择是这样做:

Rectangle pagesize = new Rectangle(img.getScaledWidth(), img.getScaledHeight());
Document document = new Document(pagesize);
Run Code Online (Sandbox Code Playgroud)

如果您的文档具有不同的页面,则必须触发新页面之前使用该setPageSize()方法.

选项2:

请参阅我对问题的回答:背景图像在景观中并用iTextSharp覆盖整个pdf

代码看起来像这样(好吧,实际的代码有点不同,但这也会起作用):

Document document = new Document(PageSize.A4.rotate());
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Image image = Image.getInstance(IMAGE);
image.scaleAbsolute(PageSize.A4.rotate());
image.setAbsolutePosition(0, 0);
document.add(image);
document.close();
Run Code Online (Sandbox Code Playgroud)

在这里,我有横向A4大小的页面,我缩放图像,使其完全适合页面.这很危险,因为这会改变图像的宽高比.这可能导致图像失真.更换scaleAbsolute()通过scaleToFit()将避免这样的问题,但你有一些白色的利润如果图像的宽高比是从页面的纵横比不同.

重要提示:请注意我setAbsolutePosition(0, 0);在两种情况下都使用过.我正在介绍此行,以便图像的左下角与页面的左下角重合.如果不这样做,您将看到底部和左侧的边距,您的图像将被剪切到顶部和右侧.