» Archive for the 'iText in Action' Category

Why do I get the exception ‘PdfReader not opened with owner password’

Wednesday, December 12th, 2007 by rubypdf

When I tried to decrypt a owner password protected PDF(version 1.6) with the last version of itext yesterday, I got the exception, “PdfReader not opened with owner password”, then I tried to use my native version pdfdecrypt.exe(base on iText 1.46) and pdftk , it said the PDF version does not supports. so I had to google the result, then I got the answer,

Paulo Soares said,
From iText version 2.0.3 and iTextSharp 4.0.4 the password restrictions are enforced by the library instead of passing that responsability to the developer. Using PdfStamper or importing pages in PdfStamper, PdfCopy and PdfWriter will throw an exception if the PDF was not opened with the owner password.

then I tried iText 2.0.2, it works.

btw, I also find another solution from PDFSharp, and I notice a very interesting comment,

PDFsharp doesn’t try to protect the document because this make little sence for an open source library.

so why PdfReader try to protect the PDF?

How to replace images in a PDF?

Wednesday, December 12th, 2007 by rubypdf

Here’s the code to replace images in PDFs, in Java and C#. It will replace the first image in the first page.

PdfReader pdf = new PdfReader("in.pdf");
PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("c:\\out.pdf"));
PdfWriter writer = stp.getWriter();
Image img = Image.getInstance("image.png");
PdfDictionary pg = pdf.getPageN(1);
PdfDictionary res =
  (PdfDictionary)PdfReader.getPdfObject(pg.get(PdfName.RESOURCES));
PdfDictionary xobj =
  (PdfDictionary)PdfReader.getPdfObject(res.get(PdfName.XOBJECT));
if (xobj != null) {
  for (Iterator it = xobj.getKeys().iterator(); it.hasNext(); ) {
    PdfObject obj = xobj.get((PdfName)it.next());
    if (obj.isIndirect()) {
      PdfDictionary tg = (PdfDictionary)PdfReader.getPdfObject(obj);
      PdfName type =
        (PdfName)PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
      if (PdfName.IMAGE.equals(type)) {
        PdfReader.killIndirect(obj);
        Image maskImage = img.getImageMask();
        if (maskImage != null)
          writer.addDirectImageSimple(maskImage);
        writer.addDirectImageSimple(img, (PRIndirectReference)obj);
        break;
      }
    }
  }
}
stp.close();
PdfReader pdf = new PdfReader("in.pdf");
PdfStamper stp = new PdfStamper(pdf, new FileStream("out.pdf",
FileMode.Create));
PdfWriter writer = stp.Writer;
Image img = Image.GetInstance("image.png");
PdfDictionary pg = pdf.GetPageN(1);
PdfDictionary res =
  (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj =
  (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
if (xobj != null) {
  foreach (PdfName name in xobj.Keys) {
    PdfObject obj = xobj.Get(name);
    if (obj.IsIndirect()) {
      PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
      PdfName type =
        (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
      if (PdfName.IMAGE.Equals(type)) {
      PdfReader.KillIndirect(obj);
      Image maskImage = img.ImageMask;
      if (maskImage != null)
        writer.AddDirectImageSimple(maskImage);
        writer.AddDirectImageSimple(img, PRIndirectReference)obj);
        break;
      }
    }
  }
}
stp.Close();

From:http://itext.ugent.be/library/question.php?id=66

Using HtmlWorker to parse HTML snippets and convert to PDF

Wednesday, October 10th, 2007 by rubypdf

HtmlWorker Class of iTextSharp support part of html tag and css tag, with the StyleSheet, it can support more css tag. So we can use it to parse Html snippets and convert to PDF.
from HtmlWorker source code, we know it support the following html tag,

ol ul li a pre font span br p div body table td th tr i b u sub sup em strong s strike h1 h2 h3 h4 h5 h6 img

and here is example sample convert from iTextInAction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* chapter14/ParsingHtmlSnippets.java */
using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Text;
using System.IO;
 
namespace chapter14
{
 
	/// <summary> This example was written by Bruno Lowagie. It is part of the book 'iText in
	/// Action' by Manning Publications. 
	/// ISBN: 1932394796
	/// http://itext.ugent.be/itext-in-action/ 
	/// http://www.manning.com/lowagie/
	/// </summary>
 
	public class ParsingHtmlSnippets
	{		
		/// <summary> Generates a PDF file with the text 'Hello World'
		/// 
		/// </summary>
		/// <param name="">args
		/// no arguments needed here
		/// </param>
		[STAThread]
		public static void  Main(System.String[] args)
		{
			System.Console.Out.WriteLine("Chapter 14: HTML parse example");
			System.Console.Out.WriteLine("-> Parses an HTML file into PDF.");
			System.Console.Out.WriteLine("-> jars needed: iText.jar");
			System.Console.Out.WriteLine("-> resource needed: list.html");
			System.Console.Out.WriteLine("-> files generated in /results subdirectory:");
			System.Console.Out.WriteLine("   html3.pdf");
 
			Document document = new Document();
			try
			{
				StyleSheet styles = new StyleSheet();
				styles.LoadTagStyle("ol", "leading", "16,0");
 
				PdfWriter.GetInstance(document, new FileStream("html3.pdf", FileMode.Create));
				document.Open();
				System.Collections.ArrayList objects;
 
				objects = HTMLWorker.ParseToList(new StreamReader("../resources/list.htm", Encoding.Default), styles);
				for (int k = 0; k < objects.Count; ++k)
					document.Add((IElement) objects[k]);
				FontFactory.Register("c:\\windows\\fonts\\gara.ttf");
                                styles.LoadTagStyle("li", "face", "garamond");
                                styles.LoadTagStyle("span", "size", "8px");
 
				objects = HTMLWorker.ParseToList(new StreamReader("../resources/list.htm", Encoding.Default), styles);
				for (int k = 0; k < objects.Count; ++k)
					document.Add((IElement) objects[k]);
				styles.LoadStyle("sf", "color", "blue");
                                styles.LoadStyle("sf", "b", "");
                                styles.LoadStyle("classic", "color", "red");
                                styles.LoadStyle("classic", "i", "");
 
				objects = HTMLWorker.ParseToList(new StreamReader("../resources/list.htm", Encoding.Default), styles);
				for (int k = 0; k < objects.Count; ++k)
					document.Add((IElement) objects[k]);
			}
			catch (System.Exception e)
			{
				System.Console.Error.WriteLine(e.StackTrace);
 
				System.Console.Error.WriteLine(e.Message);
			}
			document.Close();
		}
	}
}

list.htm