首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用itext将图像文件插入PDF时找不到文件

使用itext将图像文件插入PDF时找不到文件
EN

Stack Overflow用户
提问于 2012-01-17 16:54:22
回答 2查看 5.2K关注 0票数 5

如何添加图片和设计页眉,页脚到pdf使用itext?我写了这个,但是找不到异常文件。

代码语言:javascript
运行
复制
Image image = Image.getInstance("\resources\image.gif");

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-17 18:06:05

看一下这个example

代码语言:javascript
运行
复制
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class CreatePDF{
    public static void main(String arg[])throws Exception{
      try{
                Document document=new Document();
                FileOutputStream fos=new FileOutputStream("C:/header-footer.pdf");
                PdfWriter writer = PdfWriter.getInstance(document, fos);
                document.open();
                Image image1 = Image.getInstance("C:/image1.jpg");
                Image image2 = Image.getInstance("C:/image2.jpg");

                image1.setAbsolutePosition(0, 0);
                image2.setAbsolutePosition(0, 0);

                PdfContentByte byte1 = writer.getDirectContent();
                PdfTemplate tp1 = byte1.createTemplate(600, 150);
                tp1.addImage(image2);

                PdfContentByte byte2 = writer.getDirectContent();
                PdfTemplate tp2 = byte2.createTemplate(600, 150);
                tp2.addImage(image1);

                byte1.addTemplate(tp1, 0, 715);
                byte2.addTemplate(tp2, 0, 0);

                Phrase phrase1 = new Phrase(byte1 + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));
                Phrase phrase2 = new Phrase(byte2 + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));

                HeaderFooter header = new HeaderFooter(phrase1, true);
                HeaderFooter footer = new HeaderFooter(phrase2, true);
                document.setHeader(header);
                document.setFooter(footer);
                document.close();
                System.out.println("File is created successfully showing header and footer.");
                }
                catch (Exception ex){
                    System.out.println(ex);

                }
            }
        }
票数 2
EN

Stack Overflow用户

发布于 2015-12-03 22:26:59

我使用以下代码从类路径中插入一个图像。当您需要包含无法从公共url访问的图像时,通常很有用。

代码语言:javascript
运行
复制
Image img = Image.getInstance(getClass().getClassLoader().getResource("MyImage.jpg"));

在我的例子中,我使用的是maven,所以我将MyImage.jpg放在src/main/resources中。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8891864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档