antann78#001
antann78#001
CC#
Created by antann78#001 on 6/2/2023 in #help
❔ Merging the First Page of PDFs Using IText7 and C#
Hello,
i have written a function to merge the first page of one PDF into another using iTextSharp, and I have used the following code:
public bool MergePagePdf(string outputFile, byte[] inputFile2, byte[] inputFile1, out string strErrore)
{
bool bRet = false;
int positionx = 0;
int positiony = 0;
strErrore = "";

try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFile, FileMode.Create));

document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page1;
PdfImportedPage page2;

PdfReader reader1 = new PdfReader(inputFile1);
PdfReader reader2 = new PdfReader(inputFile2);

document.SetPageSize(reader1.GetPageSizeWithRotation(1));
document.NewPage();

page1 = writer.GetImportedPage(reader1, 1);
page2 = writer.GetImportedPage(reader2, 1);

cb.AddTemplate(page1, 0, 0);
cb.AddTemplate(page2, positionx, positiony);

if (reader1.NumberOfPages > 1)
{
for (int i = 2; i <= reader1.NumberOfPages; i++)
{
document.SetPageSize(reader1.GetPageSizeWithRotation(i));
document.NewPage();
page1 = writer.GetImportedPage(reader1, i);
cb.AddTemplate(page1, 0, 0);
}
}

bRet = true;
}
catch (Exception e)
{
strErrore = e.Message;
bRet = false;
}

return bRet;
}
public bool MergePagePdf(string outputFile, byte[] inputFile2, byte[] inputFile1, out string strErrore)
{
bool bRet = false;
int positionx = 0;
int positiony = 0;
strErrore = "";

try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFile, FileMode.Create));

document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page1;
PdfImportedPage page2;

PdfReader reader1 = new PdfReader(inputFile1);
PdfReader reader2 = new PdfReader(inputFile2);

document.SetPageSize(reader1.GetPageSizeWithRotation(1));
document.NewPage();

page1 = writer.GetImportedPage(reader1, 1);
page2 = writer.GetImportedPage(reader2, 1);

cb.AddTemplate(page1, 0, 0);
cb.AddTemplate(page2, positionx, positiony);

if (reader1.NumberOfPages > 1)
{
for (int i = 2; i <= reader1.NumberOfPages; i++)
{
document.SetPageSize(reader1.GetPageSizeWithRotation(i));
document.NewPage();
page1 = writer.GetImportedPage(reader1, i);
cb.AddTemplate(page1, 0, 0);
}
}

bRet = true;
}
catch (Exception e)
{
strErrore = e.Message;
bRet = false;
}

return bRet;
}
I am trying to achieve the same result with the new version of IText7, but I haven't been successful. Is it possible to do it with the new version? If yes, can someone guide me on how to accomplish it? Thank you for your help.
6 replies