kuujinbo_dot_info

Concatenate / Merge PDF files and Add Content

Updated 2010-08-23. The demo page now uses this code, which requires iTextSharp 5.XX.

private void _concatAndAddContent(List<string> pdf) {
  Response.ContentType = "application/pdf";
  Response.AppendHeader(
    "Content-Disposition",
    string.Format(
      "attachment; filename={0}.pdf",
      Path.GetFileName(pdf[0])
    )
  );
  Document document = new Document(); 
  PdfCopy copy = new PdfCopy(document, Response.OutputStream);
  document.Open();
  PdfImportedPage page;
// this object **REQUIRED** to add content when concatenating PDFs
  PdfCopy.PageStamp stamp;
// image watermark/background 
  Image pdfImage = Image.GetInstance(
    Request.MapPath("cat/kuujinbo2.gif")
  );
  pdfImage.SetAbsolutePosition(200, 400);
// set transparency
  PdfGState state = new PdfGState();
  state.FillOpacity = 0.3F;
  state.StrokeOpacity = 0.3F;   

  foreach (string p in pdf) {
    string pPath = Request.MapPath(
      string.Format("cat/{0}.pdf", p)
    );
    PdfReader reader = new PdfReader(
      new RandomAccessFileOrArray(pPath), null
    );    
    int pages = reader.NumberOfPages;
// loop over document pages
    for (int i = 0; i < pages; ) {
      page = copy.GetImportedPage(reader, ++i);
      stamp = copy.CreatePageStamp(page);
      PdfContentByte cb = stamp.GetUnderContent();
      cb.SaveState();
      cb.SetGState(state);
      cb.AddImage(pdfImage);       
      stamp.AlterContents();
      copy.AddPage(page);
    }
  }
  document.Close();
}

Simple Solution

Posted 2010-08-23 for a work request to append an informational message (single-page PDF file) to a library of existing PDF documents. iTextSharp 4.XX.

private void _write(List<string> pdf) {
  Document document = null;
  PdfCopy writer = null;
  try {
    Response.ContentType = "application/pdf";
    Response.AppendHeader(
      "Content-Disposition",
      string.Format(
        "attachment; filename={0}.pdf",
        Path.GetFileName(pdf[0])
      )
    );
    document = new Document();
    writer = new PdfCopy(document, Response.OutputStream);
    document.Open();
    foreach (string lpdf in pdf) {
      string pdf_path = Request.MapPath(
        string.Format(@"cat/{0}.pdf", lpdf)
      );
      PdfReader reader = new PdfReader(
        new RandomAccessFileOrArray(pdf_path), null
      );
      int n = reader.NumberOfPages;
      // add content, page-by-page
      PdfImportedPage page;
      for (int p = 0; p < n; ) {
        ++p;
        page = writer.GetImportedPage(reader, p);
        writer.AddPage(page);
      }        
    }
  } catch {
    throw;
  } finally { 
    if (document != null && document.IsOpen() ) document.Close();
  }      
}

Links

Select PDF files to combine:
The original files: [ 1 ] | [ 2 ] | [ 3 ] | [ 4 ] | [ 5 ] | [ 6 ] | [ 7 ] | [ 8 ]