Thursday, August 21, 2014

Instantly Convert docx file into PDF using word automation service in sharepoint 2013

Instantly Convert file into PDF using word automation service in sharepoint 2013


private void SaveAsPDF(SPSite siteAsAdmin, SPWeb web, SPFile DocFile)
        {
            try
            {
                SPFolder destFolder = web.Lists.TryGetList(PdfDocLibName).RootFolder;
                SPFile destFile = null;
                destFile = destFolder.Files.Add(Path.GetFileNameWithoutExtension(DocFile.Url) + ".pdf", ConvertWordToPDF(siteAsAdmin, web, DocFile), false);
                destFile.Item.Update();
                if (destFile.CheckOutType != SPFile.SPCheckOutType.None)
                {
                    destFile.CheckIn("Checked in programatically. Document generation completed.");
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
              
        private byte[] ConvertWordToPDF(SPSite siteAsAdmin, SPWeb web, SPFile DocFile)
        {
            byte[] result = null;
            try
            {
                using (Stream read = DocFile.OpenBinaryStream())
                {
                    using (MemoryStream write = new MemoryStream())
                    {
                        // Initialise Word Automation Service
                        SyncConverter sc = new SyncConverter(wordAutomationServiceName);
                        sc.UserToken = siteAsAdmin.SystemAccount.UserToken;
                        sc.Settings.UpdateFields = true;
                        sc.Settings.OutputFormat = SaveFormat.PDF;

                        // Convert to PDF
                        ConversionItemInfo info = sc.Convert(read, write);
                        if (info.Succeeded)
                            result = write.ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
            return result;
        }


Tuesday, August 12, 2014

Merge word documents using OPEN XML SDK

Merge word documents using OPEN XML SDK

  public XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

        public XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
#region Merge documents

        private void MergeDoc(string MainDoc, string Annexure)
        {
            try
            {
                AppendPageBreak(Annexure);
                using (WordprocessingDocument myDoc = WordprocessingDocument.Open(MainDoc, true))
                {
                    string altChunkId = GetUniqueXmlItemID();
                    MainDocumentPart mainPart = myDoc.MainDocumentPart;
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML,
                        //"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
                      altChunkId);
                    using (FileStream fileStream =
                        File.Open(Annexure, FileMode.Open))
                        chunk.FeedData(fileStream);
                    XElement altChunk = new XElement(w + "altChunk",
                        new XAttribute(r + "id", altChunkId)
                    );
                    XDocument mainDocumentXDoc = GetXDocument(myDoc);
                    // Add the altChunk element after the last paragraph.
                    mainDocumentXDoc.Root
                        .Element(w + "body")
                        .Elements(w + "p")
                        .Last()
                        .AddAfterSelf(altChunk);
                    SaveXDocument(myDoc, mainDocumentXDoc);
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        private void AppendPageBreak(string sourceDoc)
        {
            try
            {
                using (WordprocessingDocument myDoc = WordprocessingDocument.Open(sourceDoc, true))
                {
                    RevisionAccepter.AcceptRevisions(myDoc);
                    //   AppendPageBreak(myDoc);
                    //
                    Body body = myDoc.MainDocumentPart.Document.Body;
                    Paragraph para = new Paragraph();
                    Run run = para.AppendChild(new Run());
                    run.AppendChild(new Text(""));
                    if (para.ParagraphProperties == null)
                    {
                        para.ParagraphProperties = new ParagraphProperties();
                    }

                    para.ParagraphProperties.PageBreakBefore = new PageBreakBefore();
                    body.InsertBeforeSelf(para);
                    //body.AppendChild(p);
                    //
                }
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        private void SaveXDocument(WordprocessingDocument myDoc,
       XDocument mainDocumentXDoc)
        {
            try
            {
                // Serialize the XDocument back into the part
                using (Stream str = myDoc.MainDocumentPart.GetStream(
                    FileMode.Create, FileAccess.Write))
                using (XmlWriter xw = XmlWriter.Create(str))
                    mainDocumentXDoc.Save(xw);
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        private XDocument GetXDocument(WordprocessingDocument myDoc)
        {
            XDocument mainDocumentXDoc = null;
            try
            {
                // Load the main document part into an XDocument          
                using (Stream str = myDoc.MainDocumentPart.GetStream())
                using (XmlReader xr = XmlReader.Create(str))
                    mainDocumentXDoc = XDocument.Load(xr);
            }
            catch (Exception ex)
            {
                ULSLogService.DisplayError(this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name, ex);
            }
            return mainDocumentXDoc;

        }

        #endregion

Sunday, August 10, 2014

Insert blank space between text/image using OPXN XML SDK

Insert blank space between text/image using OPXN XML SDK



Run run2 = new Run();
Text text2= new Text() { Space = SpaceProcessingModeValues.Preserve };
text2.Text = "                                             ";
run2.Append(text2);

Friday, August 8, 2014

Add header and footer part in word document using OPEN XML SDK

Add picture and text in header and footer part in word document using OPEN XML SDK



static void ChangeHeader(String documentPath)
        {
            // Replace header in target document with header of source document.
            using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true))
            {

                // Get the main document part
                MainDocumentPart mainDocumentPart = document.MainDocumentPart;

                // Delete the existing header and footer parts
                mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts);
                mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);

                // Create a new header and footer part
                HeaderPart headerPart = mainDocumentPart.AddNewPart<HeaderPart>();
                FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>();

                // Get Id of the headerPart and footer parts
                string headerPartId = mainDocumentPart.GetIdOfPart(headerPart);
                string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);

                GenerateHeaderPartContent(headerPart);

                GenerateFooterPartContent(footerPart);

                // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id
                IEnumerable<SectionProperties> sections = mainDocumentPart.Document.Body.Elements<SectionProperties>();

                foreach (var section in sections)
                {
                    // Delete existing references to headers and footers
                    section.RemoveAllChildren<HeaderReference>();
                    section.RemoveAllChildren<FooterReference>();

                    // Create the new header and footer reference node
                    section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId });
                    section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId });
                }
            }
        }

        static void GenerateHeaderPartContent(HeaderPart part)
        {
            Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
            header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };

            paragraphProperties1.Append(paragraphStyleId1);

            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "Header";

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            header1.Append(paragraph1);

            ImagePart imagePart = part.AddImagePart(ImagePartType.Jpeg);
            using (FileStream stream = new FileStream("Tulips.jpg", FileMode.Open))
            {
                imagePart.FeedData(stream);
            }
            AddImageToParagraph(paragraph1, part.GetIdOfPart(imagePart));

            part.Header = header1;

        }

        static void GenerateFooterPartContent(FooterPart part)
        {
            Footer footer1 = new Footer() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
            footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };

            paragraphProperties1.Append(paragraphStyleId1);

            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "Footer";

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            footer1.Append(paragraph1);

            part.Footer = footer1;
        }


private static void AddImageToParagraph(Paragraph p, string relationshipId)
        {
            // Define the reference of the image.
            Drawing element =
                 new Drawing(
                     new OPDrawingWP.Inline(
                         new OPDrawingWP.Extent() { Cx = 1999000L, Cy = 1799000L },
                         new OPDrawingWP.EffectExtent()
                         {
                             LeftEdge = 0L,
                             TopEdge = 0L,
                             RightEdge = 0L,
                             BottomEdge = 0L
                         },
                         new OPDrawingWP.DocProperties()
                         {
                             Id = (UInt32Value)1U,
                             Name = "Picture 1"
                         },
                         new OPDrawingWP.NonVisualGraphicFrameDrawingProperties(
                             new DocumentFormat.OpenXml.Drawing.GraphicFrameLocks() { NoChangeAspect = true }),
                         new OPDrawing.Graphic(
                             new OPDrawing.GraphicData(
                                 new PIC.Picture(
                                     new PIC.NonVisualPictureProperties(
                                         new PIC.NonVisualDrawingProperties()
                                         {
                                             Id = (UInt32Value)0U,
                                             Name = "New Bitmap Image.jpg"
                                         },
                                         new PIC.NonVisualPictureDrawingProperties()),
                                     new PIC.BlipFill(
                                         new OPDrawing.Blip(
                                             new OPDrawing.BlipExtensionList(
                                                 new OPDrawing.BlipExtension()
                                                 {
                                                     Uri =
                                                       "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                 })
                                         )
                                         {
                                             Embed = relationshipId,
                                             CompressionState =
                                             OPDrawing.BlipCompressionValues.Print
                                         },
                                         new OPDrawing.Stretch(
                                             new OPDrawing.FillRectangle())),
                                     new PIC.ShapeProperties(
                                         new OPDrawing.Transform2D(
                                             new OPDrawing.Offset() { X = 0L, Y = 0L },
                                             new OPDrawing.Extents() { Cx = 1999000L, Cy = 1799000L }),
                                         new OPDrawing.PresetGeometry(
                                             new OPDrawing.AdjustValueList()
                                         ) { Preset = OPDrawing.ShapeTypeValues.Rectangle }))
                             ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                     )
                     {
                         DistanceFromTop = (UInt32Value)0U,
                         DistanceFromBottom = (UInt32Value)0U,
                         DistanceFromLeft = (UInt32Value)0U,
                         DistanceFromRight = (UInt32Value)0U,
                         EditId = "50D07946"
                     });

            // Append the reference to body, the element should be in a Run.
            p.AppendChild(new Run(element));
            //wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
        }