Reputation: 200
Say, I now have a 5-page PDF called 'a.pdf' which page 2 and 4 are empty. And another 2-page PDF called 'b.pdf'. Now what I want is to copy the the first page of 'b.pdf' to page2 of 'a.pdf' and second page of 'b.pdf' to page 4 of 'a.pdf'.
I found it's quite hard to find any examples, what I found is someone provided here, http://itextsharp.10939.n7.nabble.com/Replace-Pages-with-ItextSharp-td2956.html Called 'PdfStamper.ReplacePage()', I guess this is what I'm looking for, but I did a simple demo but didn't work out. Can someone have a check for me?
string _outMergeFile = Server.MapPath("~/11/a.pdf");
string file2 = Server.MapPath("~/11/b.pdf");
PdfReader readerA = new PdfReader(_outMergeFile);
PdfReader readerB = new PdfReader(file2);
PdfStamper cc = new PdfStamper(readerA,new MemoryStream());
cc.ReplacePage(readerB, 1, 2);
cc.ReplacePage(readerB, 2, 4);
cc.Close();
Thanks in advance.
================================================================================= Thanks to Jose's suggestion. The code works now. I'm now providing a simple sample here for others to reference.
public void MyFunction()
{
string _outMergeFile = Server.MapPath("~/11/a.pdf");
string file2 = Server.MapPath("~/11/b.pdf");
PdfReader readerA = new PdfReader(_outMergeFile);
PdfReader readerB = new PdfReader(file2);
PdfStamper cc = new PdfStamper(readerA, new FileStream(Server.MapPath("~/11/result.pdf"), FileMode.Append));
cc.ReplacePage(readerB, 1, 2);
cc.Close();
}
Upvotes: 8
Views: 2714
Reputation: 637
OK, I think I've found your problem. cc
is created in memory, and I don't see any code to save the actual changes to the file before you close it, so the alterations made to the in-memory file are lost. One option is to create it with a new FileStream ()
instead of a memory stream
Upvotes: 5