none
OpenXML read template page margins RRS feed

  • Question

  • Hi,

    I have a two paged template with mergefields that has different page margins for both the pages.

    We use OpenXML to read and replace mergefields with actual value from database.

    For each row in the dataset, a temporary document gets generated.

    Temporary document is merged into a final document for each row.

    When the final document is opened the 1st two pages merged seems to be coming up with the correct page margins from template. But moving forth the page margins continue as is from page 2.

    Is there a way to read the page margins of the temporary document and pass the details while merging?

    Thanks,

    Gayatri

    Monday, April 16, 2018 5:04 AM

Answers

  • Hi GayatriKarthik,

    You had asked,"Is there a way to read the page margins of the temporary document "

    Try to refer example below.

    PageMargin pgMar = 
        sectPr.Descendants<PageMargin>().FirstOrDefault();
    if (pgMar != null)
    {
        var top = pgMar.Top.Value;
        var bottom = pgMar.Bottom.Value;
        var left = pgMar.Left.Value;
        var right = pgMar.Right.Value;
    
        pgMar.Top = new Int32Value((int)left);
        pgMar.Bottom = new Int32Value((int)right);
        pgMar.Left = 
            new UInt32Value((uint)System.Math.Max(0, bottom));
        pgMar.Right = 
            new UInt32Value((uint)System.Math.Max(0, top));
    }

    Reference:

    Updating the Margins

    PageMargin Members

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, April 18, 2018 1:27 AM
    Moderator

All replies

  • Hi GayatriKarthik,

    You had asked,"Is there a way to read the page margins of the temporary document "

    Try to refer example below.

    PageMargin pgMar = 
        sectPr.Descendants<PageMargin>().FirstOrDefault();
    if (pgMar != null)
    {
        var top = pgMar.Top.Value;
        var bottom = pgMar.Bottom.Value;
        var left = pgMar.Left.Value;
        var right = pgMar.Right.Value;
    
        pgMar.Top = new Int32Value((int)left);
        pgMar.Bottom = new Int32Value((int)right);
        pgMar.Left = 
            new UInt32Value((uint)System.Math.Max(0, bottom));
        pgMar.Right = 
            new UInt32Value((uint)System.Math.Max(0, top));
    }

    Reference:

    Updating the Margins

    PageMargin Members

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, April 18, 2018 1:27 AM
    Moderator
  • Thanks Deepak. This is what I was searching for. I will give it a try.
    Thursday, April 19, 2018 3:07 AM
  • Hi Deepak,

    I tried to read Page Margin and append it to main document but it doesn't work as expected.

    You can see in the below images the template is a two pager with different margins for each page.

    Output - You can see in output from page 3 the margins are continuing from Page 2

    Thursday, April 19, 2018 5:58 AM
  • I checked the temporary file generation for page margins and it comes out correct. 

    When the merging happens the page margins are lost. I though of reading the page margin and add it to chunk. I used AppendChild but it threw error. Can you please let me know what am I doing wrong?

    See below my code

    //Loop through every row in the dataset
                    foreach (DataRow row in csvDataTable.Rows)
                    {
                        //counter = counter + 1;
                        CreateDictionaryFromRowValues(datasetName,row);

                        foreach (DataRow dataRow in dsData.Rows)
                        {
                            dictionary = new Dictionary<string, string>();
                            counter = counter + 1;
                            foreach (DataColumn dataColumn in dataRow.Table.Columns)
                            {
                                if (!dictionary.ContainsKey(dataColumn.ColumnName.ToUpper()))
                                {
                                    dictionary.Add(dataColumn.ColumnName.ToUpper(), dataRow[dataColumn.ColumnName].ToString());                                
                                }
                            }

                            CreateDocumentFromTemplate(templatePath, temporaryPath);
                            MergeTemporaryToDestination(counter, temporaryPath, destinationPath);
                            File.Delete(temporaryPath); //Deleting the temporary file used by process
                        }                    
                    } 

    private void MergeTemporaryToDestination(int counter, string temporaryPath, string destinationPath)
            {
                try
                {
                    if (!File.Exists(destinationPath))
                    {
                        File.Copy(temporaryPath, destinationPath);
                    }
                    else
                    {
                        using (WordprocessingDocument mainDoc = WordprocessingDocument.Open(destinationPath, true)) // Open destination word document from disk
                        {
                            string altChunkId = "AltChunkId" + counter.ToString(); // Assign different chunk id for each to be appended content
                            MainDocumentPart mainPart = mainDoc.MainDocumentPart;

    PageMargin pgMar = new PageMargin();
                    PageMargin pageMargin = new PageMargin();

                    using (var document = WordprocessingDocument.Open(temporaryPath, true))
                    {
                        var docPart = document.MainDocumentPart;
                        var sections = docPart.Document.Descendants<SectionProperties>();
                        
                        foreach (SectionProperties sectPr in sections)
                        {
                            if(pgMar.Top == null)
                            {
                                pgMar = sectPr.Descendants<PageMargin>().FirstOrDefault();
                            }                        
                        }
                    }

                    pageMargin.Top = pgMar.Top;
                    pageMargin.Bottom = pgMar.Bottom;
                    pageMargin.Left = pgMar.Left;
                    pageMargin.Right = pgMar.Right;

                   

                   //Appended page break so that documents get merged from new page
                   Paragraph para = new Paragraph(new Run((new Break() { Type = BreakValues.Page })));
                   mainPart.Document
                                .Body
                                .InsertAfter(para, mainPart.Document.Body.LastChild);

                    SectionProperties sectionProps = new SectionProperties();
                    sectionProps.Append(pageMargin);
                    mainPart.Document.Body.Append(sectionProps);

                   AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                            using (FileStream temporaryStream = File.Open(temporaryPath, FileMode.Open))
                                chunk.FeedData(temporaryStream);

                            AltChunk altChunk = new AltChunk();
                            altChunk.Id = altChunkId;
                            mainPart.Document
                                .Body
                                .InsertAfter(altChunk, mainPart.Document.Body
                                .Elements<Paragraph>().Last());
                            mainPart.Document.Save();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {

                }
            }


    • Edited by GayatriKarthik Thursday, April 19, 2018 6:36 AM added missing code
    Thursday, April 19, 2018 6:02 AM
  • Ok after a bit of trial I figured out adding the chunk is distorting the pagemargin properties set just after the page break. 

    Any help on how to get around with this issue?

    Thursday, April 19, 2018 6:37 AM
  • Hi GayatriKarthik,

    Does adding page break solves your issue?

    Or first you can try to set common margin first for all the documents.

    So when it get merged all have same margins.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, April 20, 2018 8:39 AM
    Moderator
  • Hi Deepak,

    Adding page break is not solving my issue.

    The template is set to have different margins can't actually change the margins.

    Monday, April 23, 2018 5:31 AM
  • Hi GayatriKarthik,

    Try to add section break first then after try to set margin may help you to solve your issue.

      Paragraph paragraph232 = new Paragraph();
    
            ParagraphProperties paragraphProperties220 = new ParagraphProperties();
    
            SectionProperties sectionProperties1 = new SectionProperties();
            SectionType sectionType1 = new SectionType(){ Val = SectionMarkValues.NextPage };
    
            sectionProperties1.Append(sectionType1);
    
            paragraphProperties220.Append(sectionProperties1);
    
            paragraph232.Append(paragraphProperties220);

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, April 26, 2018 2:45 AM
    Moderator
  • Hi Deepak,

    That doesn't help either. 

    Is there any way to achieve this is in OpenXML?

    Thanks,

    Gayatri

    Thursday, April 26, 2018 11:29 PM
  • Hi GayatriKarthik,

    Did you made a test with sections?

    I will try to find any other solution.

    if I get anything useful then I will try to provide you.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, April 27, 2018 1:25 AM
    Moderator