jiaming wei
jiaming wei

Reputation: 11

how to use pdfium library merge pdf files

I have two pdf files(1.pdf and 2.pdf), I try to use pdfium library these two files with c++ code, but merge file contents are incorrect, I don't know why, this is my code:

void gcutMergePDF(const OdUtf8String &mergePath, const OdUtf8StringArray &array)
{
  FPDF_InitLibrary();

  FPDF_DOCUMENT output = FPDF_CreateNewDocument();
  if (!output)
  {
    ELOG("create merge file %s failed", mergePath.c_str());
    return;
  }

  int index = 0;

  for (const auto &item : array)
  {
    ELOG("add file %s to zip", item.c_str());

    FPDF_DOCUMENT pdf = FPDF_LoadDocument(item.c_str(), NULL);
    if (!pdf)
    {
      ELOG("load file %s failed", item.c_str());
      continue;
    }

    int pageCount = FPDF_GetPageCount(pdf);
    for (int i = 0; i < pageCount; ++i)
    {
      FPDF_PAGE page = FPDF_LoadPage(pdf, i);
      if (!page)
      {
        ELOG("load file %s page %d failed", item.c_str(), i);
        continue;
      }

      double width = FPDF_GetPageWidth(page);
      double height = FPDF_GetPageHeight(page);
      FPDF_PAGE newPage = FPDFPage_New(output, index, width, height);
      if (!newPage)
      {
        ELOG("new page %d failed", index);
        continue;
      }

      int count = FPDFPage_CountObjects(page);
      for (int j = 0; j < count; j++)
      {
        FPDF_PAGEOBJECT object = FPDFPage_GetObject(page, j);
        if (!object)
        {
          FPDFPage_InsertObject(newPage, object);
          FPDFPage_GenerateContent(newPage);
        }
      }
      
      FPDF_ClosePage(newPage);

      FPDF_ClosePage(page);

      index++;
    }

    FPDF_CloseDocument(pdf);
  }

  FPDF_FILEWRITE writer; 
  writer.version = 1;
  writer.WriteBlock = blockWriter;
  FPDF_SaveAsCopy(output, &writer, FPDF_NO_INCREMENTAL);

  FPDF_CloseDocument(output);

  FPDF_DestroyLibrary();
}

I hope merge file include 1.pdf and 2.pdf contents, but execute this code, merge file contents are null, could somebody give me suggests?

Upvotes: 0

Views: 211

Answers (1)

Studlyer
Studlyer

Reputation: 29

You might consider having a look at the FPDF_ImportPages api found in the fpdf_ppo.h public header. I think it might do most of the heavy lifting of what you are trying to do

Upvotes: 0

Related Questions