none
OpenXML read template page margins

    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

    lundi 16 avril 2018 05:04

Réponses

  • 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.

    mercredi 18 avril 2018 01:27
    Modérateur

Toutes les réponses

  • 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.

    mercredi 18 avril 2018 01:27
    Modérateur
  • Thanks Deepak. This is what I was searching for. I will give it a try.
    jeudi 19 avril 2018 03:07
  • 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

    jeudi 19 avril 2018 05:58
  • 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
                {

                }
            }


    • Modifié GayatriKarthik jeudi 19 avril 2018 06:36 added missing code
    jeudi 19 avril 2018 06:02
  • 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?

    jeudi 19 avril 2018 06:37
  • 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.

    vendredi 20 avril 2018 08:39
    Modérateur
  • Hi Deepak,

    Adding page break is not solving my issue.

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

    lundi 23 avril 2018 05:31
  • 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.

    jeudi 26 avril 2018 02:45
    Modérateur
  • Hi Deepak,

    That doesn't help either. 

    Is there any way to achieve this is in OpenXML?

    Thanks,

    Gayatri

    jeudi 26 avril 2018 23:29
  • 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.

    vendredi 27 avril 2018 01:25
    Modérateur