web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Suggested answer

PdfSharp MemoryStream Merge files

(0) ShareShare
ReportReport
Posted on by 170

Hello,

I need a bit of advice on how I can refactor my code. Right now I created it using FileStream and it works quite fine, the next step is to make it work with MemorySteam which I don't really get on.

       
        if (packingSlipCounter > 1)
        {
            for(int i = 1; i <=conLen(pslip); i  )
            {
                custPackingSlipJour = CustPackingSlipJour::findFromCustPackingSlipTrans(conPeek(refid, i), conPeek(pslip, i), conPeek(datephys, i));
                select docuRef
                where docuRef.RefCompanyId == custPackingSlipJour.DataAreaId &&
                      docuRef.RefTableId == custPackingSlipJour.TableId &&
                      docuRef.RefRecId == custPackingSlipJour.RecId &&
                      docuRef.TypeId == Parameters.DocuTypeId;

            if (docuRef && Parameters.Cloud == NoYes::Yes)
            {
                System.IO.MemoryStream attachmentStream = new System.IO.MemoryStream();

                using (System.IO.Stream docuRefStream = DocumentManagement::getAttachmentStream(docuRef))
                {
                    docuRefStream.CopyTo(attachmentStream);
                }
                
                System.Byte[] binData2;
                binData2 = attachmentStream.ToArray();
                gotcmr = true;
                cmrFileCounter  ;
            }
            else if (docuRef)
            {
                System.IO.Stream stream = DocumentManagement::getAttachmentStream(docuRef);
                cmrFile = filePath   docuRef.originalFileName();
                System.IO.FileStream fileStream = new System.IO.FileStream(cmrFile, System.IO.FileMode::Create, System.IO.FileAccess::ReadWrite);
                stream.CopyTo(fileStream);
                fileStream.Close();
                cmrfilename = conIns(cmrfilename, cmrFileCounter   1, docuRef.originalFileName());
                gotcmr = true;
                cmrFileCounter  ;
            }

        }
        
        private void MergePDF()
    {
        PdfSharp.Pdf.PdfDocument outPutPDFDocument = new PdfSharp.Pdf.PdfDocument();
        PdfSharp.Pdf.PdfDocument inputPDFDocument = new PdfSharp.Pdf.PdfDocument();
        PdfSharp.Pdf.PdfPages pdfPages;

        int i, j, pageCount;
        FileName pdfFile;
        InteropPermission permission;
        str errorMessage;
  
        try
        {
            permission = new InteropPermission(InteropKind::ClrInterop);
            permission.assert();

            for (i = 1; i <= conLen(cmrfilename); i  )
            {
                pdfFile = filePath   conPeek(cmrfilename,i);
                inputPDFDocument = PdfSharp.Pdf.IO.PdfReader::Open(pdfFile, PdfSharp.Pdf.IO.PdfDocumentOpenMode::Import);
                outputPDFDocument.set_Version(inputPDFDocument.get_Version());
                pageCount = inputPDFDocument.get_PageCount();
                pdfPages = inputPDFDocument.get_Pages();

                if (pageCount > 0)
                {
                    for (j = 0 ; j < pageCount; j  )
                    {
                        outputPDFDocument.AddPage(pdfPages.get_Item(j));
                    }
                }
            }
            outputPDFDocument.Save(filePath   "MergedCMR.pdf");
            CodeAccessPermission::revertAssert();
            cmrFile = filePath   "MergedCMR.pdf";
        }

        catch(Exception::CLRError)
        {
            errorMessage = AifUtil::getClrErrorMessage();
            CodeAccessPermission::revertAssert();
            throw error(errorMessage);
        }
    }

I have the same question (0)
  • Martin Dráb Profile Picture
    236,320 Most Valuable Professional on at
    RE: PdfSharp MemoryStream Merge files

    Can you tell us more about your problem, please? Do you know that you can pass a stream to PdfReader::Open()?

    Also, couldn't you simplify your code by removing things unrelated to your question (such as querying tables)? It would help us (including yourself) to focus on the problem.

  • RadekM Profile Picture
    170 on at
    RE: PdfSharp MemoryStream Merge files

    My problem is to pass a stream into PdfSharp. I don't even know if I need to create a container for streamattachments or the array itself is enogh to pass all the PDF's I want to merge.

    Its enough to go PdfReader::Open(bindata2, Import)?

  • Suggested answer
    Martin Dráb Profile Picture
    236,320 Most Valuable Professional on at
    RE: PdfSharp MemoryStream Merge files

    You said you wanted a stream, but the type of bindata2 is System.Byte[, not a stream.

    If you want a stream, it's possible, as I said. If you look into source code, you'll see that there is an overload of Open() method accepting a stream:

    public static PdfDocument Open(Stream stream, PdfDocumentOpenMode openmode)
    {
      return Open(stream, null, openmode);
    }

  • WillWU Profile Picture
    22,361 on at
    RE: PdfSharp MemoryStream Merge files

    Hi RadekM,

    As Martin said, the type of bindata2 is byte[ in your code.

    You need to convert it to stream:

    System.IO.MemoryStream  stream =  new System.IO.MemoryStream(bindata2);
    

    Then you can use the open method.

    PdfReader::Open(stream, Import)

  • RadekM Profile Picture
    170 on at
    RE: PdfSharp MemoryStream Merge files

    Ok so... what I want is get all attachments and send them to another method to merge into one and save the output into table.

    So doing it this way is good? I don't know if it replaces the stream everytime the loop pass. And it it does replace, how to add it / keep it so it can be passed into the second method.

    Either how to use this stream in another method and look for all the streams I created. The MemoryStream is also attached to filename/?

         
          private int64 GetCMRREC()
          {
      for(int i = 1; i <=conLen(pslip); i  )
       if (docuRef )
                {
                    System.IO.MemoryStream attachmentStream = new System.IO.MemoryStream();
    
                    using (System.IO.Stream docuRefStream = DocumentManagement::getAttachmentStream(docuRef))
                    {
                        docuRefStream.CopyTo(attachmentStream);
                    }
                    cmrfilename = conIns(cmrfilename, cmrFileCounter   1, docuRef.originalFileName());
                    multipleDocuRefRecId = conIns(multipleDocuRefRecId, cmrFileCounter   1, docuRef.recid);
    
                    cmrFileCounter  ;
                }
                
                if (i == conLen(pslip) && cmrFileCounter > 1 )
                {
                    this.MergePDF();
                    
                }
                }
                
                
        private void MergePDF()
        {
        
        for (i = 1; i <= conLen(cmrfilename); i  )
                    {
                        //pdfFile = filePath   conPeek(cmrfilename,i);
                        inputPDFDocument = PdfSharp.Pdf.IO.PdfReader::Open(attachmentStream, PdfSharp.Pdf.IO.PdfDocumentOpenMode::Import);
                        outputPDFDocument.set_Version(inputPDFDocument.get_Version());
                        pageCount = inputPDFDocument.get_PageCount();
                        pdfPages = inputPDFDocument.get_Pages();
    
                        if (pageCount > 0)
                        {
                            for (j = 0 ; j < pageCount; j  )
                            {
                                outputPDFDocument.AddPage(pdfPages.get_Item(j));
                            }
                        }
                    }
                    }
                outputPDFDocument.Save(attachmentStream);
                CodeAccessPermission::revertAssert();

  • Suggested answer
    Martin Dráb Profile Picture
    236,320 Most Valuable Professional on at
    RE: PdfSharp MemoryStream Merge files

    No, MemoryStream has nothing to do with files. As the name suggests, the data is stored in memory. The fact that you want to hold multiple PDF files in memory may be a problem from memory-consumption perspect, therefore make sure you thing about it (apply some limits if needed).

    What your GetCMRREC() method does looks wrong to me. It ignores PdfReader completely it tries to merge just by attaching them to the same stream. I would be very suprised if it worked. The right design would be opening each file (using PdfReader::Open() discussed above), reading their pages and adding them to outputPDFDocument. You already have the logic in MergePDF(), just call it for each file instead of trying to merge files before calling MergePDF().

  • RadekM Profile Picture
    170 on at
    RE: PdfSharp MemoryStream Merge files

    Correct me if im wrong here now (most propably I am).

    I could remove the whole memory stream from GerCMRrEC() and pass just docuref recids in a container.

    After that I could open the streams direct from Pdfreader yes?

    So the last piece would be the opening string. Like this?

    System.IO.Stream stream = DocumentManagement::getAttachmentStream(docuRef);
    
    PdfSharp.Pdf.IO.PdfReader::Open(stream, PdfSharp.Pdf.IO.PdfDocumentOpenMode::Import);

  • Martin Dráb Profile Picture
    236,320 Most Valuable Professional on at
    RE: PdfSharp MemoryStream Merge files

    Whether your read file contents in GetCMRREC() and pass them to MergePDF(), or you do it all inside MergePDF(), is just implementation detail.

    Yes, you must open PDF documents with PdfReader::Open(), but it's not the last piece. Opening it's just the beginning, then you need to read pages and add them to the PDF document where you want the merged data. As I said, you already have that code in MergePDF().

  • Anjaney Profile Picture
    424 on at
    RE: PdfSharp MemoryStream Merge files

    hI RadekM , 

    Were you able to fix your issue, if yes would you be able to share the code?. Thanks in advance.   

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 2,047

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 885 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 592 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans