Archive for the 'iTextSharp(iText#)' Category

How to replace images in a PDF?

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

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • BlinkList
  • blogmarks
  • blogtercimlap
  • connotea
  • DotNetKicks
  • Fark
  • Fleck
  • Gwar
  • Haohao
  • IndianPad
  • Internetmedia
  • LinkaGoGo
  • MyShare
  • Netscape
  • NewsVine
  • Rec6
  • Reddit
  • Scoopeo
  • Slashdot
  • StumbleUpon
  • Technorati
  • Webride

the source code of cjkdemo.aspx on my free asp.net hosting

Recently, there are many people asked the source code of cjkdemo.aspx on my free asp.net hosting, so I decide release it here, there is no special.
to run it, you need iTextSharp, iTextAsian-1.0.dll and iTextAsianCmaps-1.0.dll, you can download them from http://itextsharp.sourceforge.net/.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using iTextSharp.text;
using iTextSharp.text.pdf;

public partial class CJKDemo : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        txtMessage.Text = string.Empty;
    }
    protected void btnConvert_Click(object sender, EventArgs e)
    {
        try
        {
            Document document = new Document();
            //Document.Compress = false;
            try
            {
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetExpires(DateTime.Now.AddSeconds(5));
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename=CJKDemo.pdf");
                //BaseFont.AddToResourceSearch(MapPath(@".\itextsharpasian\") + "iTextAsian-1.0.dll");
                //BaseFont.AddToResourceSearch(MapPath(@".\itextsharpasian\") + "iTextAsianCmaps-1.0.dll");
                PdfWriter.GetInstance(document, Response.OutputStream);

                //PdfWriter.GetInstance(document, new FileStream(@"E:\java\Japanese.pdf", FileMode.Create));
                document.Open();

                BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

                Font font1 = new Font(bf, 12, Font.NORMAL);
                Paragraph par = null;
                ChapterAutoNumber charp = null;
				 par = new Paragraph("iTextSharp支持中文输出", font1);
				 charp = new ChapterAutoNumber(par);
                for (int i = 0; i < 20; i++)
                {
                    document.Add(charp);
		            document.Add(new Paragraph(txtMessage.Text, font1));
                }

            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.Write(ex.Message);
                return;
            }
            document.Close();
        }
        catch (Exception)
        {
            throw;
        }
        Response.End();
    }
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • BlinkList
  • blogmarks
  • blogtercimlap
  • connotea
  • DotNetKicks
  • Fark
  • Fleck
  • Gwar
  • Haohao
  • IndianPad
  • Internetmedia
  • LinkaGoGo
  • MyShare
  • Netscape
  • NewsVine
  • Rec6
  • Reddit
  • Scoopeo
  • Slashdot
  • StumbleUpon
  • Technorati
  • Webride

Using HtmlWorker to parse HTML snippets and convert to PDF

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.

/* 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
{

	///  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/
	/// 

	public class ParsingHtmlSnippets
	{
		///  Generates a PDF file with the text 'Hello World'
		///
		/// 
		///
args
		/// no arguments needed here
		/// 
		[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

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • BlinkList
  • blogmarks
  • blogtercimlap
  • connotea
  • DotNetKicks
  • Fark
  • Fleck
  • Gwar
  • Haohao
  • IndianPad
  • Internetmedia
  • LinkaGoGo
  • MyShare
  • Netscape
  • NewsVine
  • Rec6
  • Reddit
  • Scoopeo
  • Slashdot
  • StumbleUpon
  • Technorati
  • Webride