---
title: "itext生成PDF时生成图片的问题"
author: "wnzz95391511"
date: "2009-04-29T15:13:11Z"
tags: []
categories: ["非技术"]
slug: "itext-pdf"
draft: false
lastmod: "2009-04-29T15:13:11Z"
id: 376691
url: "https://perfectlife.iteye.com/blog/376691"
---

最近需要做一个报告生成，需要生成PDF格式，就采用了itext。
在网上也学习了许多itext的使用，报告生成的程序也能跑起来了，却发现了一个问题：
**在报告生成的过程中，生成的图片与段落文章并不是按照所调用的顺序生成的。**
例如，我期望生成的格式：
标题一
图片一
标题二
图片二
标题三
图片三

由于图片二比较大，无法与上面的内容共用一个页面，那么图片二就自动被切割到下一页了。而上一页剩余的空白，由于标题三可以被容纳下，就把标题三放入了上一页。
生成结果如下：

标题一
图片一
标题二
标题三
图片二
图片三

在网上寻找了很久，可能用这的人也不多，也很多没有用到存储图片，没有找到这方面的问题。**IT人，就要执着。**凭着这份执着，我先是在itext的API中寻找有没有设置顺序的方法，找了Image类，Document类，PdfWriter类，没有寻找到结果。
我也想试试能不能把图片放入到Paragraph中，这样按照段落的形式，就不会出现逆序了。没有这样的方法。
只能到itext官方网站上，下载所有关于Image的例子看，终于发现了这个方法：
利用PdfWriter类的setStrictImageSequence(boolean ) 方法，便能解决问题。  :( 苦难啊，一个小方法，找了那么久！
例子：摘自itext官方

```java

public static void main(String[] args) {
        
        System.out.println("ImageSequence");
        
        // step 1: creation of a document-object
        Document document = new Document();
        
        try {
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter.getInstance(document, new FileOutputStream("notInSequence.pdf"));
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("inSequence.pdf"));
            writer.setStrictImageSequence(true);
            
            // step 3: we open the document
            document.open();
            
            // step 4:
            document.add(new Paragraph("1st image"));
            Image jpg = Image.getInstance("otsoe.jpg");
            document.add(jpg);
            document.add(new Paragraph("2nd image"));
            Image gif= Image.getInstance("getacro.gif");
            document.add(gif);
            document.add(new Paragraph("3rd image"));
            document.add(jpg);
            document.add(new Paragraph("4th image"));
            document.add(gif);
            document.add(new Paragraph("5th image"));
            document.add(jpg);
            document.add(new Paragraph("6th image"));
            document.add(gif);
            document.add(new Paragraph("7th image"));
            document.add(jpg);
        }
        catch(DocumentException de) {
            System.err.println(de.getMessage());
        }
        catch(IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        
        // step 5: we close the document
        document.close();
    }

```