10. สิ่งผิดปกติ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 10-11  โปรแกรมเพิ่มภาพฉากหลังลงในแฟ้ม PDF
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class PDFBackground {
  public static void main(String[] args) {
    String inFile = "c:/java101/input.pdf";
    String outFile = "c:/java101/output.pdf";
    String watermarkFile = "c:/java101/background.gif";
    try {
      PdfReader in = new PdfReader(inFile);
      PdfStamper out = new PdfStamper(in,  
                             new FileOutputStream(outFile));
      Image img = loadImage(watermarkFile);
      img.setAbsolutePosition(0, 0);
      int n = in.getNumberOfPages();
      for (int i = 1; i <= n; i++)
        out.getUnderContent(i).addImage(img);
      out.close();
    } catch (FileNotFoundException e) {
      System.out.println("ไม่พบแฟ้ม " + e.getMessage());
    } catch (DocumentException e) {
      System.out.println("มีปัญหากับเอกสาร" + e.getMessage());
    } catch (IOException e) {
      System.out.println("มีปัญหาเกี่ยวกับแฟ้ม " + e.getMessage());
    }
  }
  private static Image loadImage(String imageFile)  
                                 throws FileNotFoundException {
    String[] types = {"jpg", "jpeg", "gif", "png", "bmp" };
    int k = imageFile.lastIndexOf(".");
    String fn = imageFile;
    if (k >= 0) fn = imageFile.substring(0, k);
    String errMsg = "";
    for (int i = 0; i < types.length; i++) {
      try {
        return Image.getInstance(fn + "." + types[i]);
      } catch (Exception e) {
        errMsg += e.getMessage() + "\n";
      }
    }
    throw new FileNotFoundException(errMsg);
  }
}
©2009 S.Prasitjutrakul