Пример #1
54
        public void generateReport(Client client)
        {
            string fileNameWithDate = "PlanOfCare(" + client.ClientID + client.FirstName + " " +
                client.LastName + ") " + DateTime.Now.Month + "." + DateTime.Now.Day +
                "." + DateTime.Now.Year + " " + DateTime.Now.Hour + "." + DateTime.Now.Minute +
                "." + DateTime.Now.Second;
            this.filePath = @"C:\MyClients\WordReports\" + fileNameWithDate + ".docx";
            string xmlStylePath = @"C:\MyClients\References\styles.xml";
            this.contentType = "application/msword";
            this.fileName = client.LastName + "_" + client.FirstName + "_PlanOfCare.docx";

            #region create document part
            // todo: make filename unique
            WordprocessingDocument document = WordprocessingDocument.Create(
                this.filePath,
                WordprocessingDocumentType.Document
            );

            // create "document" part
            MainDocumentPart mainDocumentPart = document.AddMainDocumentPart();
            mainDocumentPart.Document = new Document();
            // create body of the document
            Body documentBody = new Body();
            mainDocumentPart.Document.Append(documentBody);
            #endregion

            #region create style part
            // create "style" part
            StyleDefinitionsPart styleDefinitionsPart =
                mainDocumentPart.AddNewPart<StyleDefinitionsPart>();
            // open style xml

            // todo: reference this xml locally somehow
            FileStream stylesTemplate =
                new FileStream(xmlStylePath, FileMode.Open, FileAccess.Read);
            styleDefinitionsPart.FeedData(stylesTemplate);
            styleDefinitionsPart.Styles.Save();
            #endregion

            #region create title
            // create paragraph for title
            Paragraph titleParagraphe = new Paragraph();
            // create paragraph properties
            ParagraphProperties titleProperties = new ParagraphProperties();

            // todo: figure out more styles and how these styles work
            // make the paragraph a "title"
            titleProperties.ParagraphStyleId = new ParagraphStyleId { Val = "Title" };

            // apply the style properties to the paragraph
            titleParagraphe.Append(titleProperties);

            // create RUN, append TEXT to RUN, append RUN to PARAGRAPH
            Run titleRun = new Run();
            Text titleText = new Text("Plan of Care for " + client.FirstName + " " + client.LastName);
            titleRun.Append(titleText);
            titleParagraphe.Append(titleRun);

            // append PARAGRAPH to BODY
            documentBody.Append(titleParagraphe);
            #endregion

            #region create first heading (Client Details)
            // add client name
            Paragraph clientDetailsHeadingParagraph = new Paragraph();

            // create styling
            ParagraphProperties clientDetailsHeadingProperties = new ParagraphProperties();
            clientDetailsHeadingProperties.ParagraphStyleId = new ParagraphStyleId { Val = "Heading1" };
            clientDetailsHeadingParagraph.Append(clientDetailsHeadingProperties);

            // create run/text of client info
            Run clientDetailsHeadingRun = new Run();
            Text clientDetailsHeadingText = new Text("Contact Information");

            // append text to document
            clientDetailsHeadingRun.Append(clientDetailsHeadingText);
            clientDetailsHeadingParagraph.Append(clientDetailsHeadingRun);
            documentBody.Append(clientDetailsHeadingParagraph);
            #endregion

            // create details table
            Table addressTable = new Table();

            #region address label
            // create row/cell for address label
            TableRow addressLabelRow = new TableRow();
            TableCell addressLabelCell = new TableCell();
            Paragraph addressLabelPgh = new Paragraph();

            // create paragraph properties
            addressLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create run properties
            RunProperties addressLabelRunProperties = new RunProperties();
            addressLabelRunProperties.Append(new Bold());
            // create label text to append to cell
            Run addressLabelRun = new Run();
            addressLabelRun.Append(addressLabelRunProperties);
            Text addressLabelText = new Text("Address: ");
            addressLabelRun.Append(addressLabelText);
            addressLabelPgh.Append(addressLabelRun);

            addressLabelCell.Append(addressLabelPgh);
            // add cell to row
            addressLabelRow.Append(addressLabelCell);
            #endregion

            #region address row 1
            // create row/cell for address label
            TableRow address1ValueRow = new TableRow();
            TableCell address1ValueCell = new TableCell();
            Paragraph address1ValuePgh = new Paragraph();

            // create paragraph properties
            address1ValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create label text to append to cell
            Run address1ValueRun = new Run();
            Text address1ValueText = new Text(client.Address.Address1 + " " + client.Address.Address2);
            address1ValueRun.Append(address1ValueText);
            address1ValuePgh.Append(address1ValueRun);
            address1ValueCell.Append(address1ValuePgh);
            // add cell to row
            address1ValueRow.Append(address1ValueCell);
            #endregion

            #region city row
            // create row/cell for address label
            TableRow cityValueRow = new TableRow();
            TableCell cityValueCell = new TableCell();
            Paragraph cityValuePgh = new Paragraph();

            // create paragraph properties
            cityValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create label text to append to cell
            Run cityValueRun = new Run();
            Text cityValueText = new Text(client.Address.City);
            cityValueRun.Append(cityValueText);
            cityValuePgh.Append(cityValueRun);
            cityValueCell.Append(cityValuePgh);
            // add cell to row
            cityValueRow.Append(cityValueCell);
            #endregion

            #region state row
            // create row/cell for address label
            TableRow stateValueRow = new TableRow();
            TableCell stateValueCell = new TableCell();
            Paragraph stateValuePgh = new Paragraph();

            // create paragraph properties
            stateValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create label text to append to cell
            Run stateValueRun = new Run();
            Text stateValueText = new Text(client.Address.State);
            stateValueRun.Append(stateValueText);
            stateValuePgh.Append(stateValueRun);
            stateValueCell.Append(stateValuePgh);
            // add cell to row
            stateValueRow.Append(stateValueCell);
            #endregion

            #region zip row
            // create row/cell for address label
            TableRow zipValueRow = new TableRow();
            TableCell zipValueCell = new TableCell();
            Paragraph zipValuePgh = new Paragraph();

            // create paragraph properties
            zipValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create label text to append to cell
            Run zipValueRun = new Run();
            Text zipValueText = new Text(client.Address.Zip);
            zipValueRun.Append(zipValueText);
            zipValuePgh.Append(zipValueRun);
            zipValueCell.Append(zipValuePgh);
            // add cell to row
            zipValueRow.Append(zipValueCell);
            #endregion

            #region write address table to doc
            addressTable.Append(
                addressLabelRow,
                address1ValueRow,
                cityValueRow,
                stateValueRow,
                zipValueRow
            );

            // append table to doc body
            documentBody.Append(addressTable);
            #endregion

            #region create second heading (Client Details)
            // add client name
            Paragraph spacerParagraph = new Paragraph();
            // create paragraph properties
            spacerParagraph.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            Run spacerRun = new Run();

            // append text to document
            documentBody.Append(spacerParagraph);
            #endregion

            Table contactInfoTable = new Table();

            // create first row of details (2 properties)
            TableRow firstDetailRow = new TableRow();

            #region email label and value
            // email label in first row of details
            TableCell emailLabelCell = new TableCell();
            Paragraph emailLabelPgh = new Paragraph();

            // create paragraph properties
            emailLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create email label run properties
            RunProperties emailLabelRunProperties = new RunProperties();
            emailLabelRunProperties.Append(new Bold());

            Run emailLabelRun = new Run();
            emailLabelRun.Append(emailLabelRunProperties);
            Text emailLabelText = new Text("Email:");
            emailLabelRun.Append(emailLabelText);
            emailLabelPgh.Append(emailLabelRun);
            emailLabelCell.Append(emailLabelPgh);

            // create cell for email value
            TableCell emailValueCell = new TableCell();
            Paragraph emailValuePgh = new Paragraph();

            // create paragraph properties
            emailValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run emailValueRun = new Run();
            Text emailValueText = new Text(client.Email);
            emailValueRun.Append(emailValueText);
            emailValuePgh.Append(emailValueRun);
            emailValueCell.Append(emailValuePgh);
            #endregion

            #region home phone label and value
            // email label in first row of details
            TableCell homePhoneLabelCell = new TableCell();
            Paragraph homePhoneLabelPgh = new Paragraph();

            // create paragraph properties
            homePhoneLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create email label run properties
            RunProperties homePhoneLabelRunProperties = new RunProperties();
            homePhoneLabelRunProperties.Append(new Bold());

            Run homePhoneLabelRun = new Run();
            homePhoneLabelRun.Append(homePhoneLabelRunProperties);
            Text homePhoneLabelText = new Text("Home Phone: ");
            homePhoneLabelRun.Append(homePhoneLabelText);
            homePhoneLabelPgh.Append(homePhoneLabelRun);
            homePhoneLabelCell.Append(homePhoneLabelPgh);

            // create cell for email value
            TableCell homePhoneValueCell = new TableCell();
            Paragraph homePhoneValuePgh = new Paragraph();

            // create paragraph properties
            homePhoneValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run homePhoneValueRun = new Run();
            Text homePhoneValueText = new Text(client.HomePhoneNumber);
            homePhoneValueRun.Append(homePhoneValueText);
            homePhoneValuePgh.Append(homePhoneValueRun);
            homePhoneValueCell.Append(homePhoneValuePgh);

            // add cells to row
            firstDetailRow.Append(emailLabelCell, emailValueCell, homePhoneLabelCell, homePhoneValueCell);
            #endregion

            // create second row of details (2 properties)
            TableRow secondDetailRow = new TableRow();

            #region cellphone label and value
            // cellPhone label in first row of details
            TableCell cellPhoneLabelCell = new TableCell();
            Paragraph cellPhoneLabelPgh = new Paragraph();

            // create paragraph properties
            cellPhoneLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create cellPhone label run properties
            RunProperties cellPhoneLabelRunProperties = new RunProperties();
            cellPhoneLabelRunProperties.Append(new Bold());

            Run cellPhoneLabelRun = new Run();
            cellPhoneLabelRun.Append(cellPhoneLabelRunProperties);
            Text cellPhoneLabelText = new Text("Cell Phone:");
            cellPhoneLabelRun.Append(cellPhoneLabelText);
            cellPhoneLabelPgh.Append(cellPhoneLabelRun);
            cellPhoneLabelCell.Append(cellPhoneLabelPgh);

            // create cell for cellPhone value
            TableCell cellPhoneValueCell = new TableCell();
            Paragraph cellPhoneValuePgh = new Paragraph();

            // create paragraph properties
            cellPhoneValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run cellPhoneValueRun = new Run();
            Text cellPhoneValueText = new Text(client.CellPhoneNumber);
            cellPhoneValueRun.Append(cellPhoneValueText);
            cellPhoneValuePgh.Append(cellPhoneValueRun);
            cellPhoneValueCell.Append(cellPhoneValuePgh);
            #endregion

            #region work phone label and value
            // email label in first row of details
            TableCell workPhoneLabelCell = new TableCell();
            Paragraph workPhoneLabelPgh = new Paragraph();

            // create paragraph properties
            workPhoneLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create email label run properties
            RunProperties workPhoneLabelRunProperties = new RunProperties();
            workPhoneLabelRunProperties.Append(new Bold());

            Run workPhoneLabelRun = new Run();
            workPhoneLabelRun.Append(workPhoneLabelRunProperties);
            Text workPhoneLabelText = new Text("Work Phone: ");
            workPhoneLabelRun.Append(workPhoneLabelText);
            workPhoneLabelPgh.Append(workPhoneLabelRun);
            workPhoneLabelCell.Append(workPhoneLabelPgh);

            // create cell for email value
            TableCell workPhoneValueCell = new TableCell();
            Paragraph workPhoneValuePgh = new Paragraph();

            // create paragraph properties
            workPhoneValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run workPhoneValueRun = new Run();
            Text workPhoneValueText = new Text(client.WorkPhoneNumber);
            workPhoneValueRun.Append(workPhoneValueText);
            workPhoneValuePgh.Append(workPhoneValueRun);
            workPhoneValueCell.Append(workPhoneValuePgh);

            // add cells to row
            secondDetailRow.Append(cellPhoneLabelCell, cellPhoneValueCell, workPhoneLabelCell, workPhoneValueCell);
            #endregion

            #region write contact information table to doc
            contactInfoTable.Append(
                firstDetailRow,
                secondDetailRow);

            // append table to doc body
            documentBody.Append(contactInfoTable);
            #endregion

            #region create second heading (Demographics)
            // add client name
            Paragraph demographicsHeadingParagraph = new Paragraph();

            // create styling
            ParagraphProperties demographicsHeadingProperties = new ParagraphProperties();
            demographicsHeadingProperties.ParagraphStyleId = new ParagraphStyleId { Val = "Heading1" };
            demographicsHeadingParagraph.Append(demographicsHeadingProperties);

            // create run/text of client info
            Run demographicsHeadingRun = new Run();
            Text demographicsHeadingText = new Text("Demographics");

            // append text to document
            demographicsHeadingRun.Append(demographicsHeadingText);
            demographicsHeadingParagraph.Append(demographicsHeadingRun);
            documentBody.Append(demographicsHeadingParagraph);
            #endregion

            // create demographics table
            Table demographicsTable = new Table();

            // create first row of demographic info (2 properties)
            TableRow firstDemoRow = new TableRow();

            #region ss label and value
            // ss label in first row of details
            TableCell SsLabelCell = new TableCell();
            Paragraph SsLabelPgh = new Paragraph();

            // create paragraph properties
            SsLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create Ss label run properties
            RunProperties SsLabelRunProperties = new RunProperties();
            SsLabelRunProperties.Append(new Bold());

            Run SsLabelRun = new Run();
            SsLabelRun.Append(SsLabelRunProperties);
            Text SsLabelText = new Text("Social Security Number:");
            SsLabelRun.Append(SsLabelText);
            SsLabelPgh.Append(SsLabelRun);
            SsLabelCell.Append(SsLabelPgh);

            // create cell for Ss value
            TableCell SsValueCell = new TableCell();
            Paragraph SsValuePgh = new Paragraph();

            // create paragraph properties
            SsValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });
            // create value run
            Run SsValueRun = new Run();
            Text SsValueText = new Text(client.SocialNum);
            SsValueRun.Append(SsValueText);
            SsValuePgh.Append(SsValueRun);
            SsValueCell.Append(SsValuePgh);
            #endregion

            #region date of birth label and value
            // email label in first row of details
            TableCell DobLabelCell = new TableCell();
            Paragraph DobLabelPgh = new Paragraph();

            // create paragraph properties
            DobLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create email label run properties
            RunProperties DobLabelRunProperties = new RunProperties();
            DobLabelRunProperties.Append(new Bold());

            Run DobLabelRun = new Run();
            DobLabelRun.Append(DobLabelRunProperties);
            Text DobLabelText = new Text("Date of Birth: ");
            DobLabelRun.Append(DobLabelText);
            DobLabelPgh.Append(DobLabelRun);
            DobLabelCell.Append(DobLabelPgh);

            // create cell for email value
            TableCell DobValueCell = new TableCell();
            Paragraph DobValuePgh = new Paragraph();

            // create paragraph properties
            DobValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run DobValueRun = new Run();
            Text DobValueText = new Text();
            if (client.DateOfBirth != null)
                DobValueText.Text = Convert.ToString(client.DateOfBirth.Value.ToShortDateString());
            else
                DobValueText.Text = Convert.ToString(client.DateOfBirth);
            DobValueRun.Append(DobValueText);
            DobValuePgh.Append(DobValueRun);
            DobValueCell.Append(DobValuePgh);

            // add cells to row
            firstDemoRow.Append(SsLabelCell, SsValueCell, DobLabelCell, DobValueCell);
            #endregion

            // create second row of demographic info (2 properties)
            TableRow secondDemoRow = new TableRow();

            #region gender label and value
            // gender label in first row of details
            TableCell genderLabelCell = new TableCell();
            Paragraph genderLabelPgh = new Paragraph();

            // create paragraph properties
            genderLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create gender label run properties
            RunProperties genderLabelRunProperties = new RunProperties();
            genderLabelRunProperties.Append(new Bold());

            Run genderLabelRun = new Run();
            genderLabelRun.Append(genderLabelRunProperties);
            Text genderLabelText = new Text("Gender:");
            genderLabelRun.Append(genderLabelText);
            genderLabelPgh.Append(genderLabelRun);
            genderLabelCell.Append(genderLabelPgh);

            // create cell for gender value
            TableCell genderValueCell = new TableCell();
            Paragraph genderValuePgh = new Paragraph();

            // create paragraph properties
            genderValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run genderValueRun = new Run();
            Text genderValueText = new Text(client.Gender.GenderName);
            genderValueRun.Append(genderValueText);
            genderValuePgh.Append(genderValueRun);
            genderValueCell.Append(genderValuePgh);
            #endregion

            #region age label and value
            // email label in first row of details
            TableCell ageLabelCell = new TableCell();
            Paragraph ageLabelPgh = new Paragraph();

            // create paragraph properties
            ageLabelPgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create email label run properties
            RunProperties ageLabelRunProperties = new RunProperties();
            ageLabelRunProperties.Append(new Bold());

            Run ageLabelRun = new Run();
            ageLabelRun.Append(ageLabelRunProperties);
            Text ageLabelText = new Text("Age: ");
            ageLabelRun.Append(ageLabelText);
            ageLabelPgh.Append(ageLabelRun);
            ageLabelCell.Append(ageLabelPgh);

            // create cell for email value
            TableCell ageValueCell = new TableCell();
            Paragraph ageValuePgh = new Paragraph();

            // create paragraph properties
            ageValuePgh.Append(new ParagraphProperties
            {
                SpacingBetweenLines = new SpacingBetweenLines { After = "0" }
            });

            // create value run
            Run ageValueRun = new Run();
            Text ageValueText = new Text();
            int age = new Utility().getAge(client.DateOfBirth);
            if (age != 0)
                ageValueText.Text = Convert.ToString(age);
            else
                ageValueText.Text = null;
            ageValueRun.Append(ageValueText);
            ageValuePgh.Append(ageValueRun);
            ageValueCell.Append(ageValuePgh);

            // add cells to row
            secondDemoRow.Append(genderLabelCell, genderValueCell, ageLabelCell, ageValueCell);
            #endregion

            // create 3rd row of demographic info (1 property)
            TableRow thirdDemoRow = new TableRow();

            #region marital status label and value
            // email label in first row of details
            TableCell maritalStatusLabelCell = new TableCell();

            // create email label run properties
            RunProperties maritalStatusLabelRunProperties = new RunProperties();
            maritalStatusLabelRunProperties.Append(new Bold());

            Run maritalStatusLabelRun = new Run();
            maritalStatusLabelRun.Append(maritalStatusLabelRunProperties);
            Text maritalStatusLabelText = new Text("Marital Status:");
            maritalStatusLabelRun.Append(maritalStatusLabelText);
            maritalStatusLabelCell.Append(new Paragraph(maritalStatusLabelRun));

            // create cell for email value
            TableCell maritalStatusValueCell = new TableCell();
            // create value run
            Run maritalStatusValueRun = new Run();
            Text maritalStatusValueText = new Text(client.MaritalStatus.MaritalStatusName);
            maritalStatusValueRun.Append(maritalStatusValueText);
            maritalStatusValueCell.Append(new Paragraph(maritalStatusValueRun));

            // add cells to row
            thirdDemoRow.Append(maritalStatusLabelCell, maritalStatusValueCell);
            #endregion

            #region write demographics table to doc
            demographicsTable.Append(firstDemoRow, secondDemoRow, thirdDemoRow);

            // append table to doc body
            documentBody.Append(demographicsTable);
            #endregion

            #region insert background html

            // create temp html file to insert
            string fullHtml = "<html><body>" + client.Background + "</body></html>";

            StreamWriter sw = File.CreateText(@"C:\MyClients\References\tmp.html");
            sw.WriteLine(fullHtml);
            sw.Close();

            // create alt chunk that is inserted into document
            string altChunkId = "MyAltChunkId";
            AlternativeFormatImportPart chunk =
                mainDocumentPart.AddAlternativeFormatImportPart(
                AlternativeFormatImportPartType.Html,
                altChunkId);
            chunk.FeedData(File.Open(@"C:\MyClients\References\tmp.html", FileMode.Open));
            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;
            mainDocumentPart.Document.Append(altChunk);

            #endregion

            // save doc and release
            document.MainDocumentPart.Document.Save();
            document.Dispose();
        }
Пример #2
2
		// 05/12/2011   Add ability to append chunks. 
		// http://blogs.msdn.com/b/ericwhite/archive/2008/10/27/how-to-use-altchunk-for-document-assembly.aspx
		public static void AppendAltChunk(WordprocessingDocument docx, int nID, byte[] byChunk)
		{
			string altChunkId = "AltChunkId" + nID.ToString();
			MainDocumentPart mainPart = docx.MainDocumentPart;
			if ( mainPart == null )
			{
				mainPart = docx.AddMainDocumentPart();
				mainPart.AddNewPart<WebSettingsPart>("rId3");
				mainPart.AddNewPart<DocumentSettingsPart>("rId2");
				mainPart.AddNewPart<StyleDefinitionsPart>("rId1");
				mainPart.AddNewPart<ThemePart>("rId5");
				mainPart.AddNewPart<FontTablePart>("rId4");
				mainPart.Document = new Document();
				mainPart.Document.Body = new Body();
			}
			AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
			using ( MemoryStream stmChunk = new MemoryStream() )
			{
				stmChunk.Write(byChunk, 0, byChunk.Length);
				stmChunk.Seek(0, SeekOrigin.Begin);
				chunk.FeedData(stmChunk);
			}
			AltChunk altChunk = new AltChunk();
			altChunk.Id = altChunkId;
			mainPart.Document.Body.InsertAt<AltChunk>(altChunk, mainPart.Document.Body.Elements().Count());
			//mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
		}
Пример #3
0
        /// <summary>
        /// Method that writes the XML data to the template
        /// </summary>
        /// <param name="root">A <see cref="XElement"/> containing the XML form field data.</param>
        public void WriteXMLToFields(XElement root)
        {
            // Write PAF form fields
            XElement job            = root.Element("JobDescription");
            string   assessmentType = root.Element("SelectedPAFType").Value;
            RunFonts checkBoxRun    = new RunFonts {
                Ascii = "Wingdings"
            };
            RunProperties checkBoxRunProperties = new RunProperties();

            checkBoxRunProperties.Append(checkBoxRun);
            switch (assessmentType)
            {
            case "Periodic Performance Assessment":
                PAF_PeriodicPerformanceAssessment.Write("\u2713", true, checkBoxRunProperties);
                break;

            case "Probationary Midpoint":
                PAF_ProbationaryMidpoint.Write("\u2713", true, checkBoxRunProperties);
                break;

            case "Rating Justification":
                PAF_RatingJustification.Write("\u2713", true, checkBoxRunProperties);
                break;
            }

            PAF_EmployeeName.Write($"{root.Element("LastName").Value}, {root.Element("FirstName").Value}");
            PAF_PayrollId.Write(root.Element("PayrollIdNumber").Value);
            PAF_StartDate.Write(DateTime.Parse(root.Element("StartDate").Value).ToString("MM/dd/yy"));
            PAF_EndDate.Write(DateTime.Parse(root.Element("EndDate").Value).ToString("MM/dd/yy"));
            PAF_ClassGrade.Write($"{job.Element("ClassTitle").Value} / {job.Element("Grade").Value}");
            PAF_DistrictDivision.Write(root.Element("DepartmentDivision").Value);
            // HTML from the RTF Textarea needs to be chunked.
            using (Stream chunkStream = PAF_Assessment_Chunk.GetStream(FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter stringStream = new StreamWriter(chunkStream))
                {
                    stringStream.Write($"<html>{root.Element("Assessment").Value}</html>");
                }
            }
            AltChunk assessmentChunk = new AltChunk
            {
                Id = "assessmentChunk"
            };

            PAF_Assessment.Paragraph.InsertBeforeSelf(assessmentChunk);
            using (Stream chunkStream = PAF_Recommendations_Chunk.GetStream(FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter stringStream = new StreamWriter(chunkStream))
                {
                    stringStream.Write($"<html>{root.Element("Recommendation").Value}</html>");
                }
            }
            AltChunk recommendationsChunk = new AltChunk
            {
                Id = "recommendationsChunk"
            };

            PAF_Recommendations.Paragraph.InsertBeforeSelf(recommendationsChunk);
        }
Пример #4
0
        /// <summary>
        /// Write docx
        /// </summary>
        /// <param name="bookMark"></param>
        /// <param name="filePath"></param>
        /// <param name="html"></param>
        private void WriteDocx(string bookMark, string filePath, string html)
        {
            try
            {
                string stringToWrite = "<html><head><meta charset=\"UTF-8\"></head><body>" + html + "</body></html>";

                MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(stringToWrite));

                using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
                {
                    MainDocumentPart mainPart = doc.MainDocumentPart;

                    IEnumerable <BookmarkStart> rs = from bm in mainPart.Document.Body.Descendants <BookmarkStart>() where bm.Name == bookMark select bm;

                    DocumentFormat.OpenXml.OpenXmlElement bookmark = rs.SingleOrDefault();

                    if (bookmark != null)
                    {
                        DocumentFormat.OpenXml.OpenXmlElement parent = bookmark.Parent;
                        AltChunk altchunk = new AltChunk();
                        string   chunkId  = bookMark + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
                        altchunk.Id = chunkId;
                        AlternativeFormatImportPart formatImport = doc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, chunkId);
                        formatImport.FeedData(memoryStream);
                        parent.InsertBeforeSelf(altchunk);
                    }
                }
            }
            catch (Exception ext)
            {
                throw ext;
            }
        }
        /// <summary>
        /// 將包含 HTML 的內容設定至指定的書籤內
        /// (已知問題: 若 HTML 包含圖片,圖片部分會異常無法顯示,待解決)
        /// </summary>
        /// <param name="doc">文件</param>
        /// <param name="BookmarkName">書籤名稱 (有區分大小寫)</param>
        /// <param name="Html">HTML內容</param>
        /// <param name="DeleteAFterSetvalue">是否在設定完書籤內容後,將書籤移除 (預設: True)</param>
        private void SetBookmarkValueWithHtmlValue(WordprocessingDocument doc, string BookmarkName, string Html, bool DeleteAfterSetvalue = true)
        {
            StringBuilder xhtmlBuilder = new StringBuilder();

            xhtmlBuilder.Append("<HTML>");
            xhtmlBuilder.Append("<body>");
            xhtmlBuilder.Append(Html);
            xhtmlBuilder.Append("</body>");
            xhtmlBuilder.Append("</HTML >");

            string altChunkId = "chunk_" + BookmarkName.ToLower();
            AlternativeFormatImportPart chunk = doc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId);

            using (MemoryStream xhtmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xhtmlBuilder.ToString())))
            {
                chunk.FeedData(xhtmlStream);

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                var res = from bm in doc.MainDocumentPart.Document.Body.Descendants <BookmarkStart>()
                          where bm.Name == BookmarkName
                          select bm;
                var bookmark = res.SingleOrDefault();
                var parent   = bookmark.Parent;
                parent.InsertAfterSelf(altChunk);


                if (bookmark != null && DeleteAfterSetvalue)
                {
                    bookmark.Remove();
                }
            }
        }
        /// <summary>
        /// Append SubDocument at end of current doc
        /// </summary>
        /// <param name="content"></param>
        public void AppendSubDocument(Stream content, bool withPageBreak)
        {
            if (wdDoc == null)
            {
                throw new InvalidOperationException("Document not loaded");
            }

            AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

            formatImportPart.FeedData(content);

            AltChunk altChunk = new AltChunk();

            altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart);

            wdMainDocumentPart.Document.Body.Elements <Paragraph>().Last().InsertAfterSelf(altChunk);

            if (withPageBreak)
            {
                Paragraph p = new Paragraph(
                    new Run(
                        new Break()
                {
                    Type = BreakValues.Page
                }));
                altChunk.InsertAfterSelf(p);
            }
        }
Пример #7
0
        public WordManipulator AppendOtherWordFile(String wordFilePath, Boolean addPageBreak = true)
        {
            MainDocumentPart            mainPart   = _document.MainDocumentPart;
            string                      altChunkId = "AltChunkId" + Guid.NewGuid().ToString();
            AlternativeFormatImportPart chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

            using (FileStream fileStream = File.Open(wordFilePath, FileMode.Open))
            {
                chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                .Body
                .InsertAfter(altChunk, mainPart.Document.Body
                             .Elements().LastOrDefault());
                mainPart.Document.Save();
            }
            if (addPageBreak)
            {
                _body.Append(
                    new Paragraph(
                        new Run(
                            new Break()
                {
                    Type = BreakValues.Page
                })));
            }
            return(this);
        }
Пример #8
0
        //gavdcodeend 06

        //gavdcodebegin 07
        public static void WordOpenXmlJoinTwoDocuments()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                string           altChunkId = "ID" + Guid.NewGuid().ToString();
                MainDocumentPart mainPart   = myWordDoc.MainDocumentPart;

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

                using (FileStream fileStream =
                           File.Open(@"C:\Temporary\WordDoc02.docx", FileMode.Open))

                    myChunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk
                {
                    Id = altChunkId
                };
                mainPart.Document.Body
                .InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>()
                             .Last());
                mainPart.Document.Save();
            }
        }
Пример #9
0
        /// <summary>
        /// Set html content.
        /// </summary>
        /// <param name="label"></param>
        /// <param name="parent"></param>
        /// <param name="documentPart"></param>
        /// <param name="formatImportPart"></param>
        /// <returns></returns>
        private static AltChunk SetHtmlContent(Label label, OpenXmlElement parent, OpenXmlPart documentPart, AlternativeFormatImportPart formatImportPart)
        {
            AltChunk altChunk = new AltChunk();

            altChunk.Id = documentPart.GetIdOfPart(formatImportPart);

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(label.Text)))
            {
                formatImportPart.FeedData(ms);
            }

            OpenXmlElement paragraph = null;

            if (parent is DocumentFormat.OpenXml.Wordprocessing.Paragraph)
            {
                paragraph = parent;
            }
            else
            {
                paragraph = parent.Ancestors <DocumentFormat.OpenXml.Wordprocessing.Paragraph>().FirstOrDefault();
            }

            if (paragraph != null)
            {
                paragraph.InsertAfterSelf(altChunk);
            }

            return(altChunk);
        }
Пример #10
0
        public void MergeFromLocal(ICollection <string> docsLocalPaths, string destinationPath)
        {
            if (File.Exists(destinationPath))
            {
                File.Delete(destinationPath);
            }

            File.Copy(docsLocalPaths.First(), destinationPath);
            docsLocalPaths = docsLocalPaths.Skip(1).ToList();

            using (var wordDocument = WordprocessingDocument.Open(destinationPath, true))
            {
                var mainPart = wordDocument.MainDocumentPart;

                foreach (var secondaryFilePath in docsLocalPaths)
                {
                    using (var secondaryFile = new FileStream(secondaryFilePath, FileMode.OpenOrCreate))
                    {
                        var altChunkId = "AltChunkId" + Guid.NewGuid().ToString();
                        var chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                        chunk.FeedData(secondaryFile);

                        var altChunk = new AltChunk();
                        altChunk.Id = altChunkId;
                        wordDocument.MainDocumentPart.Document.Body.Append(altChunk);
                    }
                }

                mainPart.Document.Save();
            }
        }
Пример #11
0
        public byte[] ConvertByMht(List<string> sectionCustomDatas)
        {
            var embeddedResourceName = Constants.HtmlToWord.TemplateFileName;
            var ms = Utility.GetMemoryStreamFromEmbeddedResource(embeddedResourceName);
            _fileStream = ms;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                int altChunkIdCounter = 1;
                int blockLevelCounter = 1;

                foreach (var sectionCustomData in sectionCustomDatas)
                {//get mht

                    //MHTConverter.ConvertWebPageToMHTString()
                    string altChunkId = String.Format("AltChunkId{0}", altChunkIdCounter);
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Mht, altChunkId);

                    using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
                    {
                        using (var stringWriter = new StreamWriter(chunkStream, Encoding.UTF8))
                        {
                            stringWriter.Write(sectionCustomData);
                        }
                    }
                    var altChunk = new AltChunk { Id = altChunkId };
                    altChunkIdCounter++;
                    mainPart.Document.Body.InsertAt(altChunk, blockLevelCounter);
                }
                mainPart.Document.Save();
            }

            return GetFileAsBytes(ms);
        }
         private static byte[] Merge(byte[] dest, byte[] src)
         {
             string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString();
 
             var memoryStreamDest = new MemoryStream();
             memoryStreamDest.Write(dest, 0, dest.Length);
             memoryStreamDest.Seek(0, SeekOrigin.Begin);
             var memoryStreamSrc = new MemoryStream(src);
 
             using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true))
             {
                 MainDocumentPart mainPart = doc.MainDocumentPart;
                 AlternativeFormatImportPart altPart =
                     mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                 altPart.FeedData(memoryStreamSrc);
                 var altChunk = new AltChunk();
                 altChunk.Id = altChunkId;
                               OpenXmlElement lastElem = mainPart.Document.Body.Elements<AltChunk>().LastOrDefault();
             if(lastElem == null)
             {
                 lastElem = mainPart.Document.Body.Elements<Paragraph>().Last();
             }
             //Page Brake einfügen
             Paragraph pageBreakP = new Paragraph();
             Run pageBreakR = new Run();
             Break pageBreakBr = new Break() { Type = BreakValues.Page };
             pageBreakP.Append(pageBreakR);
             pageBreakR.Append(pageBreakBr);                
 
             return memoryStreamDest.ToArray();
         }
     }
Пример #13
0
        public void HtmlToWordPartial(string html, string destinationFileName)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(destinationFileName, WordprocessingDocumentType.Document))
            {
                string altChunkId = "myId";

                MainDocumentPart mainPart = wordDocument.MainDocumentPart;
                if (mainPart == null)
                {
                    mainPart = wordDocument.AddMainDocumentPart();
                    new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart);
                }
                MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(html)).ToArray());

                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainPart.Document.Body.Append(altChunk);
                wordDocument.Save();
                wordDocument.Close();
            }
        }
Пример #14
0
        public WordManipulator AppendHtml(OpenXmlElement refChild, String htmlPage)
        {
            AltChunk altChunk = CreateChunkForHtmlPage(htmlPage);

            _document.MainDocumentPart.Document.Body.InsertAfter(altChunk, refChild);
            return(this);
        }
Пример #15
0
        public byte[] Convert(string htmlAsString)
        {
            var embeddedResourceName = Constants.HtmlToWord.TemplateFileName;
            var ms = Utility.GetMemoryStreamFromEmbeddedResource(embeddedResourceName);
            _fileStream = ms;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                const int altChunkIdCounter = 1;
                const int blockLevelCounter = 1;

                string altChunkId = String.Format("AltChunkId{0}", altChunkIdCounter);
                AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);

                using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
                {
                    using (var stringWriter = new StreamWriter(chunkStream, Encoding.UTF8))
                    {
                        stringWriter.Write(htmlAsString);
                    }
                }
                var altChunk = new AltChunk { Id = altChunkId };
                mainPart.Document.Body.InsertAt(altChunk, blockLevelCounter);
                mainPart.Document.Save();
            }

            return GetFileAsBytes(ms);
        }
Пример #16
0
        private static void CombinarDocumentos(List <string> anexos, MainDocumentPart documentoBase)
        {
            if (anexos != null)
            {
                if (anexos.Count > 0)
                {
                    foreach (var anexo in anexos)
                    {
                        AlternativeFormatImportPart chunk =
                            documentoBase.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

                        using (FileStream fileStream = File.Open(anexo, FileMode.Open))
                        {
                            chunk.FeedData(fileStream);
                        }

                        AltChunk altChunk = new AltChunk()
                        {
                            Id = documentoBase.GetIdOfPart(chunk)
                        };

                        Paragraph saltoPagina = new Paragraph(new Run(new Break()
                        {
                            Type = BreakValues.Page
                        }));

                        documentoBase.Document.Body.AppendChild(saltoPagina);
                        documentoBase.Document.Body.AppendChild(altChunk);
                    }

                    //documentoBase.Document.Save();
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Combines the documents specified and combines them in this document with a page break
        /// between each one.
        /// </summary>
        /// <param name="docLocations">The document locations.</param>
        /// <returns>This</returns>
        public WordDocumentAssembler CombineDocuments(List <string> docLocations)
        {
            if (docLocations is null ||
                docLocations.Count == 0 ||
                InternalWordDoc is null ||
                InternalWordDoc.MainDocumentPart is null)
            {
                return(this);
            }

            var mainPart = InternalWordDoc.MainDocumentPart;

            for (var x = 0; x < docLocations.Count; ++x)
            {
                var chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);
                var altChunkId = mainPart.GetIdOfPart(chunk);
                using var fileStream = File.Open(docLocations[x], FileMode.Open);
                chunk.FeedData(fileStream);
                var altChunk = new AltChunk
                {
                    Id = altChunkId
                };
                AppendPageBreak();
                mainPart.Document
                .Body
                ?.Append(altChunk);
            }
            return(this);
        }
Пример #18
0
        static void DocxMerge(string srcFile1, string srcFile2, string outFile)
        {
            File.Delete(outFile);
            File.Copy(srcFile1, outFile);

            using (WordprocessingDocument myDoc =
                       WordprocessingDocument.Open(outFile, true))
            {
                string                      altChunkId = "AltChunkId1";
                MainDocumentPart            mainPart   = myDoc.MainDocumentPart;
                AlternativeFormatImportPart chunk      =
                    mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML,
                        altChunkId);

                using (FileStream fileStream = File.Open(srcFile2,
                                                         FileMode.Open))
                    chunk.FeedData(fileStream);

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainPart.Document.Body.InsertAfter(altChunk,
                                                   mainPart.Document.Body.Elements <Paragraph>().Last());
                mainPart.Document.Save();
            }
        }
Пример #19
0
        public void Update(DocumentFormat.OpenXml.Wordprocessing.Tag tag, string value, MainDocumentPart mainPart)
        {
            string mainhtml = "<html><head><style type='text/css'>.catalogGeneralTable{border-collapse: collapse;text-align: left;} .catalogGeneralTable td, th{ padding: 5px; border: 1px solid #999999; } </style></head> <body style='font-family:Trebuchet MS;font-size:.9em;'>" + value + "</body></html>";


            int    blockLevelCounter = 1;
            string altChunkId        = String.Format("AltChunkId{0}", altChunkIdCounter++);

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

            using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter stringWriter = new StreamWriter(chunkStream, Encoding.UTF8)) //Encoding.UTF8 is important to remove special characters
                {
                    stringWriter.Write(mainhtml);
                }
            }

            AltChunk altChunk = new AltChunk();

            altChunk.Id = altChunkId;

            SdtBlock sdtBlock = tag.Ancestors <SdtBlock>().Single();

            sdtBlock.InsertAt(altChunk, blockLevelCounter++);
        }
Пример #20
0
        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: mono {0} inputfile.html outputfile.docx",
                                  System.AppDomain.CurrentDomain.FriendlyName);
                return;
            }

            string inputFile  = args[0];
            string outputFile = args[1];

            using (WordprocessingDocument myDoc =
                       WordprocessingDocument.Create(
                           outputFile, WordprocessingDocumentType.Document))
            {
                string           altChunkId = "AltChunkId1";
                MainDocumentPart mainPart   = myDoc.AddMainDocumentPart();
                mainPart.Document      = new Document();
                mainPart.Document.Body = new Body();
                var chunk = mainPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.Html, altChunkId);
                using (FileStream fileStream =
                           File.Open(inputFile, FileMode.Open))
                {
                    chunk.FeedData(fileStream);
                }
                AltChunk altChunk = new AltChunk()
                {
                    Id = altChunkId
                };
                mainPart.Document.Append(altChunk);
                mainPart.Document.Save();
            }
        }
Пример #21
0
        //OpenXML Word中写入html
        private void button9_Click(object sender, EventArgs e)
        {
            string docName = @"openxmltest-copy.docx";

            File.Copy(@"openxmltest.docx", docName, true);
            using (WordprocessingDocument doc = WordprocessingDocument.Open(docName, true))
            {
                string           altChunkId  = "myId";
                MainDocumentPart mainDocPart = doc.MainDocumentPart;

                var run       = new DocumentFormat.OpenXml.Wordprocessing.Run(new Text("test"));
                var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new ParagraphProperties(
                                                                                        new Justification()
                {
                    Val = JustificationValues.Center
                }),
                                                                                    run);

                //RunProperties runProperties = new RunProperties(); //属性

                //RunFonts fonts = new RunFonts() { EastAsia = "DFKai-SB" }; // 设置字体
                //FontSize size = new FontSize() { Val = "52" }; // 设置字体大小
                //DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "red" }; // 设置字体样式

                //// 将样式添加到属性里面
                //runProperties.Append(color);
                //runProperties.Append(size);
                //runProperties.Append(fonts);

                //run.Append(runProperties);
                //paragraph.Append(run);

                var body = mainDocPart.Document.Body;
                body.Append(paragraph);

                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body><h1>HELLO</h1></body></html>"));
                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                using (StreamReader reader = new StreamReader("苏州抵押合同模板.html")) //苏州抵押合同模板.html 苏州借款合同模板-3月.html
                {
                    string content = reader.ReadToEnd();
                    ms = new MemoryStream(Encoding.UTF8.GetBytes(content));
                }

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart =
                    mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                body.Append(altChunk);
                //mainDocPart.Document.Save();
            }
        }
Пример #22
0
        private string Compose(string[] sourceFiles, string outputFile)
        {
            string altChunkIdBase  = "acID";
            int    altChunkCounter = 1;
            string altChunkId      = altChunkIdBase + altChunkCounter.ToString();

            // 选择第一个文件为主文件,保留里面的样式
            string masterFile = sourceFiles[0];

            File.Copy(masterFile, outputFile, true);

            // 后续文件合并进来
            List <string> fileList = sourceFiles.ToList();

            fileList.RemoveAt(0);

            // 打开目标文件进行合并
            MainDocumentPart wdDocTargetMainPart = null;
            Document         docTarget           = null;
            AlternativeFormatImportPartType afType;

            using (WordprocessingDocument wdPkgTarget = WordprocessingDocument.Open(outputFile, true))
            {
                wdDocTargetMainPart = wdPkgTarget.MainDocumentPart;

                docTarget = wdDocTargetMainPart.Document;
                Paragraph           lastParaTarget = docTarget.Body.Descendants <Paragraph>().Last();
                ParagraphProperties paraPropTarget = lastParaTarget.ParagraphProperties;
                if (paraPropTarget == null)
                {
                    paraPropTarget = new ParagraphProperties();
                }
                Run paraRun = lastParaTarget.Descendants <Run>().FirstOrDefault();

                foreach (string fi in fileList)
                {
                    afType = AlternativeFormatImportPartType.WordprocessingML;
                    AlternativeFormatImportPart chunk            = wdDocTargetMainPart.AddAlternativeFormatImportPart(afType, altChunkId);
                    System.IO.FileStream        fsSourceDocument = new FileStream(fi, FileMode.Open);
                    chunk.FeedData(fsSourceDocument);
                    //Create the chunk
                    AltChunk ac = new AltChunk
                    {
                        //Link it to the part
                        Id = altChunkId
                    };
                    docTarget.Body.Append(ac);
                    docTarget.Save();
                    altChunkCounter += 1;
                    altChunkId       = altChunkIdBase + altChunkCounter.ToString();
                    chunk            = null;
                    ac = null;
                }
            }

            return(outputFile);
        }
Пример #23
0
    public static int Main(string[] args)
    {
      // https://docs.microsoft.com/ja-jp/dotnet/api/documentformat.openxml.wordprocessing.altchunk?view=openxml-2.8.1

      var app = new CommandLineApplication(throwOnUnexpectedArg: false);
      app.Name = nameof(docxmerge);
      app.Description = "Mearge .docx files. ";
      app.HelpOption("-h|--help");
      app.ExtendedHelpText = @"Merged files should be the end of argument like: 
      docxmerge [options] file1 file2
      ";
      var optionTemplateFile = app.Option(
        template: "-t|--template",
        description: "Template filename. merged files will be appended after the contents of template file. ",
        optionType: CommandOptionType.SingleValue
      );

      var optionOutFile = app.Option(
        template: "-o|--output",
        description: "Output filename",
        optionType: CommandOptionType.SingleValue
      );

      app.OnExecute(() =>
      {
        var templateFile = optionTemplateFile.Value();
        var outFile = optionOutFile.Value();
        // Because position of last paragraph is not updated while looping
        var mergedFiles = app.RemainingArguments;
        mergedFiles.Reverse();
        File.Delete(outFile);
        File.Copy(templateFile, outFile);

        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outFile, true))
        {
          MainDocumentPart mainPart = myDoc.MainDocumentPart;
          foreach (var f in mergedFiles.Select((Value, Index) => new { Value, Index }))
          {
            string altChunkId = $"AltChunkId{f.Index}";
            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
              AlternativeFormatImportPartType.WordprocessingML, altChunkId
            );
            using (FileStream fileStream = File.Open(f.Value, FileMode.Open))
            {
              chunk.FeedData(fileStream);
            }
            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;
            mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());

          }
          mainPart.Document.Save();
        }
      });
      return app.Execute(args);
    }
Пример #24
0
        /// <summary>
        ///  Append a list of SubDocuments after the predecessorElement.
        /// </summary>
        /// <param name="filesToInsert"></param>
        /// <param name="insertPageBreaks"></param>
        /// <param name="predecessorElement"></param>
        private void AppendStreams(IList <MemoryStream> filesToInsert, bool insertPageBreaks, OpenXmlCompositeElement insertAfterElement)
        {
            OpenXmlCompositeElement openXmlCompositeElement = null;

            foreach (var file in filesToInsert)
            {
                using (WordprocessingDocument pkgSourceDoc = WordprocessingDocument.Open(file, true))
                {
                    var headers = pkgSourceDoc.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();
                    foreach (var header in headers)
                    {
                        header.Remove();
                    }
                    var footers = pkgSourceDoc.MainDocumentPart.Document.Descendants <FooterReference>().ToList();
                    foreach (var footer in footers)
                    {
                        footer.Remove();
                    }
                    pkgSourceDoc.MainDocumentPart.Document.Save();
                }

                string altChunkId = "AltChunkId-" + Guid.NewGuid();

                AlternativeFormatImportPart chunk = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                file.Position = 0;
                chunk.FeedData(file);

                AltChunk altChunk = new AltChunk()
                {
                    Id = altChunkId
                };

                if (openXmlCompositeElement == null)
                {
                    openXmlCompositeElement = insertAfterElement;
                }

                if (insertPageBreaks)
                {
                    var run = new Run(new Break()
                    {
                        Type = BreakValues.Page
                    });
                    Paragraph paragraph = new Paragraph(run);
                    openXmlCompositeElement.InsertAfterSelf <Paragraph>(paragraph);
                    openXmlCompositeElement = paragraph;
                }
                openXmlCompositeElement.InsertAfterSelf <AltChunk>(altChunk);
                openXmlCompositeElement = altChunk;

                if (wdDoc == null)
                {
                    throw new InvalidOperationException("Document not loaded");
                }
            }
        }
Пример #25
0
        public void setContent(byte[] byteArray)
        {
            using (MemoryStream ms = new MemoryStream(byteArray))
            {
                chunk.FeedData(ms);
            }
            AltChunk altChunk = new AltChunk();

            altChunk.Id = altChunkId;

            // Embed AltChunk after the last paragraph.
            body.InsertAfter(altChunk, body.Elements <Paragraph>().Last());
        }
Пример #26
0
        /// <summary>
        /// Generate contract document from templates
        /// Token format: Some {Name} was pushed
        /// </summary>
        /// <param name="contractTemplateId"></param>
        /// <param name="dataTokens"></param>
        /// <returns></returns>
        public virtual async Task <ResultModel <MemoryStream> > GenerateDocumentFromTemplateAsync(Guid?contractTemplateId,
                                                                                                  IDictionary <string, string> dataTokens)
        {
            var templateRequest = await FindContractTemplateByIdWithIncludesAsync(contractTemplateId);

            if (!templateRequest.IsSuccess)
            {
                return(templateRequest.Map <MemoryStream>());
            }
            var template = templateRequest.Result;



            var textHtml = template.Sections.OrderBy(o => o.Order).Aggregate("<html><head><meta charset='UTF - 8'></head><body>", (current, section) => current + section.TemplateValue);

            textHtml += "</body></html>";


            using (var memStream = new MemoryStream())
            {
                using (var wordDoc = WordprocessingDocument.Create(memStream,
                                                                   DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
                {
                    wordDoc.AddMainDocumentPart();
                    var mainDoc = new Document();
                    var body    = new Body();


                    //Inject data into template value with marked tokens
                    var textWithTokens = textHtml.Inject(new Hashtable((IDictionary)dataTokens));

                    var cid = "MainSection";
                    //var ms = new MemoryStream(Encoding.UTF8.GetBytes(textWithTokens));
                    var ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(textWithTokens)).ToArray());
                    var formatImportPart = wordDoc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, cid);
                    formatImportPart.FeedData(ms);
                    var altChunk = new AltChunk {
                        Id = cid
                    };
                    body.Append(altChunk);


                    mainDoc.AppendChild(body);
                    wordDoc.MainDocumentPart.Document = mainDoc;

                    wordDoc.Close();
                }

                return(new SuccessResultModel <MemoryStream>(memStream));
            }
        }
Пример #27
0
        private void button2_Click(object sender, EventArgs e)
        {
            //AddHeaderFromTo(@"C:\Temp\Teste1.docx", @"C:\Temp\Teste2.docx");

            using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Temp\Teste2.docx", true))
            {
                string altChunkId = "AltChunkId5";

                MainDocumentPart            mainDocPart = doc.MainDocumentPart;
                AlternativeFormatImportPart chunk       = mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf, altChunkId);

                string rtfEncodedString = richTextBox1.Rtf;

                using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString)))
                {
                    chunk.FeedData(ms);
                }

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                // Funciona adicionando na sequencia
                //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());


                //teste para adicionar no cabeçalho
                //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());

                // itera os elementos do documento
                //var paragraphs = doc.MainDocumentPart.Document.Body.Elements<Paragraph>();
                // Iterate through paragraphs, runs, and text, finding the text we want and replacing it
                //foreach (Paragraph paragraph in paragraphs)
                //{
                //    foreach (Run run in paragraph.Elements<Run>())
                //    {
                //        foreach (Text text in run.Elements<Text>())
                //        {
                //            if (text.Text == "CABEÇALHO")
                //            {
                //                text.Text = "CABEÇALHO 2";
                //           }
                //        }
                //    }
                //}

                mainDocPart.Document.Save();
            }
        }
Пример #28
0
        private void SetHtml(MainDocumentPart mainDocumentPart, string sdtBlockTag, string value, OpenXmlElement elem)
        {
            string       html       = "<html><body><div>" + value + "</div></body></html>";
            string       altChunkId = sdtBlockTag;
            MemoryStream ms         = new MemoryStream(Encoding.Default.GetBytes(html));
            AlternativeFormatImportPart formatImportPart =
                mainDocumentPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.Html, altChunkId);

            formatImportPart.FeedData(ms);
            ms.Close();
            AltChunk altChunk = new AltChunk();

            altChunk.Id = altChunkId;
            elem.Append(altChunk);
        }
Пример #29
0
        public void MergeDocument(WordprocessingDocument package, string documentPath)
        {
            string altChunkId = $"AltChunkId{Guid.NewGuid()}";

            MainDocumentPart mainPart = package.MainDocumentPart;

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

            using (FileStream fileStream = File.Open(documentPath, FileMode.Open))
                chunk.FeedData(fileStream);

            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;

            mainPart.Document.Body.AppendChild(altChunk);
        }
Пример #30
0
        public const int CharV    = 3;  //V char


        /// <summary>
        /// merge word files into one
        /// </summary>
        /// <param name="srcFiles">source word files/param>
        /// <param name="toFile">target word file</param>
        /// <param name="deleteSrc">delete source file or not</param>
        public static void MergeFiles(string[] srcFiles, string toFile, bool deleteSrc)
        {
            //copy first file to target
            File.Copy(srcFiles[0], toFile, true);

            using (var docx = WordprocessingDocument.Open(toFile, true))
            {
                var mainPart = docx.MainDocumentPart;

                //skip first file
                for (var i = 1; i < srcFiles.Length; i++)
                {
                    //add page break
                    mainPart.Document.Body.AppendChild(new Paragraph(new Run(new Break()
                    {
                        Type = BreakValues.Page
                    })));

                    //add file
                    var altChunkId = "AltChunkId" + i;
                    var chunk      = mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                    using (var fileStream = File.Open(srcFiles[i], FileMode.Open))
                    {
                        chunk.FeedData(fileStream);
                    }
                    var altChunk = new AltChunk
                    {
                        Id = altChunkId
                    };
                    mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>().Last());
                }
                mainPart.Document.Save();
                //docx.Close();
            }

            //delete source files if need
            if (deleteSrc)
            {
                foreach (var file in srcFiles)
                {
                    File.Delete(file);
                }
            }
        }
Пример #31
0
        /// <summary>
        /// Append SubDocument at end of current doc
        /// </summary>
        /// <param name="content"></param>
        /// <param name="withPageBreak">If true insert a page break before.</param>
        public void AppendSubDocument(Stream content, bool withPageBreak)
        {
            if (wdDoc == null)
            {
                throw new InvalidOperationException("Document not loaded");
            }

            AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

            formatImportPart.FeedData(content);

            AltChunk altChunk = new AltChunk();

            altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart);

            OpenXmlElement lastElement = wdMainDocumentPart.Document.Body.LastChild;

            if (lastElement is SectionProperties)
            {
                lastElement.InsertBeforeSelf(altChunk);
                if (withPageBreak)
                {
                    SectionProperties sectionProps = (SectionProperties)lastElement.Clone();
                    var p   = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    var ppr = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties();
                    p.AppendChild(ppr);
                    ppr.AppendChild(sectionProps);
                    altChunk.InsertBeforeSelf(p);
                }
            }
            else
            {
                lastElement.InsertAfterSelf(altChunk);
                if (withPageBreak)
                {
                    Paragraph p = new Paragraph(
                        new Run(
                            new Break()
                    {
                        Type = BreakValues.Page
                    }));
                    altChunk.InsertBeforeSelf(p);
                }
            }
        }
Пример #32
0
        public string Export(string tenant, string html, string fileName, string destination = "")
        {
            html = ExportHelper.RemoveNonPrintableElements(html);
            string folder = Guid.NewGuid().ToString();

            if (string.IsNullOrWhiteSpace(destination))
            {
                destination = $"/Tenants/{tenant}/Documents/{folder}/{fileName}.docx";
            }

            var file = new FileInfo(PathMapper.MapPath(destination));

            if (file.Directory != null && !file.Directory.Exists)
            {
                file.Directory.Create();
            }

            using (var doc = WordprocessingDocument.Create(file.FullName, WordprocessingDocumentType.Document))
            {
                string id = "html2doc";

                var main = doc.AddMainDocumentPart();

                main.Document = new Document();
                main.Document.AppendChild(new Body());

                var ms = new MemoryStream(Encoding.UTF8.GetBytes(html));

                var importPart = main.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, id);

                // Feed HTML data into format import part (chunk).
                importPart.FeedData(ms);
                var altChunk = new AltChunk {
                    Id = id
                };

                // ReSharper disable once PossiblyMistakenUseOfParamsMethod
                main.Document.Body.Append(altChunk);

                doc.Save();
            }

            //HtmlWriter.WriteHtml(destination, html);
            return(destination);
        }
Пример #33
0
    public WordprocessingDocument AppendDocumentToDocument(WordprocessingDocument doc_1, WordprocessingDocument doc_2)
    {
        {
            string altChunkId = "AltChunkId1";

            MainDocumentPart mainPart = doc_1.MainDocumentPart;

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

            using (FileStream fileStream = File.Open(doc_2_path, FileMode.Open))chunk.FeedData(fileStream);
            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;
            mainPart.Document
                .Body
                .InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
            mainPart.Document.Save();
        }
    }
Пример #34
0
        public void MergeFromAzure(ICollection <string> docsAzurePaths, string destinationPath)
        {
            if (docsAzurePaths != null && docsAzurePaths.Any())
            {
                var firstUrl = docsAzurePaths.First();
                docsAzurePaths = docsAzurePaths.Skip(1).ToList();

                if (File.Exists(destinationPath))
                {
                    File.Delete(destinationPath);
                }

                using (var primaryFile = new FileStream(destinationPath, FileMode.OpenOrCreate))
                {
                    this.azureBlobService.Download(primaryFile, firstUrl, false);
                }

                using (var wordDocument = WordprocessingDocument.Open(destinationPath, true))
                {
                    var mainPart = wordDocument.MainDocumentPart;

                    foreach (var url in docsAzurePaths)
                    {
                        var secondaryFilePath = Path.GetTempPath() + Guid.NewGuid().ToString() + ".docx";
                        using (var secondaryFile = new FileStream(secondaryFilePath, FileMode.OpenOrCreate))
                        {
                            this.azureBlobService.Download(secondaryFile, url, true);

                            var altChunkId = "AltChunkId" + Guid.NewGuid().ToString();
                            var chunk      = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                            chunk.FeedData(secondaryFile);

                            var altChunk = new AltChunk();
                            altChunk.Id = altChunkId;
                            wordDocument.MainDocumentPart.Document.Body.Append(altChunk);
                        }

                        File.Delete(secondaryFilePath);
                    }

                    mainPart.Document.Save();
                }
            }
        }
Пример #35
0
    private void generatedocxfile(StringBuilder strHTMLContent, string FederationName)
    {
        /*t create and init a new docx file and
         * a WordprocessingDocument object to represent it t*/

        string docPath = getPPRPath();

        //string docPath=GetSavePath();

        DocumentFormat.OpenXml.Packaging.WordprocessingDocument doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(docPath + FederationName + ".docx", WordprocessingDocumentType.Document);
        MainDocumentPart mainDocPart = doc.AddMainDocumentPart();

        mainDocPart.Document = new Document();
        Body body = new Body();

        mainDocPart.Document.Append(body);

        // Add an aFChunk part to the package
        string altChunkId = "AltChunkId1";

        AlternativeFormatImportPart chunk = mainDocPart
                                            .AddAlternativeFormatImportPart(
            AlternativeFormatImportPartType.Xhtml, altChunkId);

        string html = strHTMLContent.ToString();

        using (MemoryStream ms =
                   new MemoryStream(Encoding.UTF8.GetBytes(html)))
        {
            chunk.FeedData(ms);
        }

        // Add the aFChunk to the document
        AltChunk altChunk = new AltChunk();

        altChunk.Id = altChunkId;
        mainDocPart.Document.Body.Append(altChunk);

        /*t to save the changes t*/
        doc.MainDocumentPart.Document.Save();
        doc.Dispose();
    }
Пример #36
0
        private AltChunk CreateChunkForHtmlPage(string htmlPage)
        {
            var    realHtml   = $"<html><head></head><body>{htmlPage}</body></html>";
            string altChunkId = "myid" + Guid.NewGuid().ToString();

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(realHtml)))
            {
                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart = _document.MainDocumentPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.Html,
                    altChunkId);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
            }
            var altChunk = new AltChunk();

            altChunk.Id = altChunkId;
            return(altChunk);
        }
Пример #37
0
        /// <summary>
        ///     Given the input writes out a docx file with the request's data
        /// </summary>
        /// <param name="input">The list of strings to turn into paragraphs</param>
        /// <param name="templatePath">The location of the template on the server</param>
        /// <param name="destinationPath">Temporary path of file to write on server</param>
        /// <param name="requestId">The ID of the request to be exported</param>
        public void generateDocument(IEnumerable<string> input,
                                     string templatePath, string destinationPath,
                                     long requestId)
        {
            System.IO.File.Copy(templatePath, destinationPath);

            using (
                WordprocessingDocument document =
                    WordprocessingDocument.Open(destinationPath, true)) {
                MainDocumentPart mainPart = document.MainDocumentPart;
                int altChunkIdCounter = 1;
                int blockLevelCounter = 1;

                foreach (string s in input) {
                    string altChunkId = String.Format("AltChunkId{0}",
                                                      altChunkIdCounter++);

                    // Import data as html content using Altchunk
                    AlternativeFormatImportPart chunk =
                        mainPart.AddAlternativeFormatImportPart(
                            AlternativeFormatImportPartType.Html, altChunkId);

                    using (Stream chunkStream = chunk.GetStream(
                        FileMode.Create, FileAccess.Write)) {
                        using (var stringWriter =
                            new StreamWriter(chunkStream, Encoding.UTF8)) {
                            // Requires Encoding.UTF8 to remove special characters
                            String content;

                            if (Constants.Export.EXPORT_HEADERS.Contains(s)) {
                                content = "<h3>" + s + "</h3>";
                            } else {
                                content = s;
                            }

                            stringWriter.Write("<html><body>" + content +
                                               "</html></body>");
                            ;
                        }
                    }

                    var altChunk = new AltChunk {Id = altChunkId};

                    mainPart.Document.Body.InsertAt(altChunk,
                                                    blockLevelCounter++);
                    mainPart.Document.Save();
                }

                document.Close();
            }

            HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = Constants.Export.WORD_CONTENT_TYPE;
            response.AddHeader(Constants.Export.CONTENT_DISPOSITION,
                               Constants.Export.REQUEST_ATTACHMENT
                               + requestId + Constants.Export.WORD_FILE_EXT);
            response.TransmitFile(destinationPath);
            response.Flush();
            response.End();

            if (System.IO.File.Exists(destinationPath)) {
                System.IO.File.Delete(destinationPath);
            }
        }
Пример #38
0
        private byte[] ConvertToDoc(string html)
        {
            byte[] buf;

            using (var stream = new MemoryStream()) {
                using (var wordDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document)) {
                    //add main document part
                    var mainPart = wordDoc.AddMainDocumentPart();
                    //add body
                    var body = new Body();
                    var doc = new Document(body);
                    doc.Save(mainPart);

                    const string altChunkId = "altChunkId";

                    //Import data as html content using Altchunk
                    var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);

                    using (var chunkStream = chunk.GetStream()) {
                        using (var stringWriter = new StreamWriter(chunkStream, Encoding.UTF8)) {
                            //Encoding.UTF8 is important to remove special characters
                            stringWriter.Write(html);
                        }
                    }

                    var altChunk = new AltChunk { Id = altChunkId };

                    mainPart.Document.Body.InsertAt(altChunk, 0);
                    mainPart.Document.Save();

                    wordDoc.Close();
                }

                stream.Position = 0;

                buf = new byte[stream.Length];
                stream.Read(buf, 0, buf.Length);
            }

            return buf;
        }
Пример #39
0
        public byte[] AppendDocumentsToPrimaryDocument(byte[] primaryDocument, IList<byte[]> documentstoAppend)
        {
            if (documentstoAppend == null)
            {
                throw new ArgumentNullException("documentstoAppend");
            }

            if (primaryDocument == null)
            {
                throw new ArgumentNullException("primaryDocument");
            }

            byte[] output = null;

            using (var finalDocumentStream = new MemoryStream())
            {
                finalDocumentStream.Write(primaryDocument, 0, primaryDocument.Length);

                using (var finalDocument = WordprocessingDocument.Open(finalDocumentStream, true))
                {
                    SectionProperties finalDocSectionProperties = null;
                    UnprotectDocument(finalDocument);

                    var tempSectionProperties =
                        finalDocument.MainDocumentPart.Document.Descendants<SectionProperties>().LastOrDefault();

                    if (tempSectionProperties != null)
                    {
                        finalDocSectionProperties = tempSectionProperties.CloneNode(true) as SectionProperties;
                    }

                    this.RemoveContentControlsAndKeepContents(finalDocument.MainDocumentPart.Document);

                    foreach (byte[] documentToAppend in documentstoAppend)
                    {
                        var subReportPart =
                            finalDocument.MainDocumentPart.AddAlternativeFormatImportPart(
                                AlternativeFormatImportPartType.WordprocessingML);
                        SectionProperties secProperties = null;

                        using (var docToAppendStream = new MemoryStream())
                        {
                            docToAppendStream.Write(documentToAppend, 0, documentToAppend.Length);

                            using (var docToAppend = WordprocessingDocument.Open(docToAppendStream, true))
                            {
                                UnprotectDocument(docToAppend);

                                tempSectionProperties =
                                    docToAppend.MainDocumentPart.Document.Descendants<SectionProperties>().LastOrDefault();

                                if (tempSectionProperties != null)
                                {
                                    secProperties = tempSectionProperties.CloneNode(true) as SectionProperties;
                                }

                                this.RemoveContentControlsAndKeepContents(docToAppend.MainDocumentPart.Document);
                                docToAppend.MainDocumentPart.Document.Save();
                            }

                            docToAppendStream.Position = 0;
                            subReportPart.FeedData(docToAppendStream);
                        }

                        if (documentstoAppend.ElementAtOrDefault(0).Equals(documentToAppend))
                        {
                            AssignSectionProperties(finalDocument.MainDocumentPart.Document, finalDocSectionProperties);
                        }

                        var altChunk = new AltChunk();
                        altChunk.Id = finalDocument.MainDocumentPart.GetIdOfPart(subReportPart);
                        finalDocument.MainDocumentPart.Document.AppendChild(altChunk);

                        if (!documentstoAppend.ElementAtOrDefault(documentstoAppend.Count - 1).Equals(documentToAppend))
                        {
                            AssignSectionProperties(finalDocument.MainDocumentPart.Document, secProperties);
                        }

                        finalDocument.MainDocumentPart.Document.Save();
                    }

                    finalDocument.MainDocumentPart.Document.Save();
                }

                finalDocumentStream.Position = 0;
                output = new byte[finalDocumentStream.Length];
                finalDocumentStream.Read(output, 0, output.Length);
            }

            return output;
        }
Пример #40
0
        /// <summary>
        /// Write docx
        /// </summary>
        /// <param name="bookMark"></param>
        /// <param name="filePath"></param>
        /// <param name="html"></param>
        private void WriteDocx(string bookMark, string filePath, string html)
        {
            try
            {
                string stringToWrite = "<html><head><meta charset=\"UTF-8\"></head><body>" + html + "</body></html>";

                MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(stringToWrite));

                using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
                {
                    MainDocumentPart mainPart = doc.MainDocumentPart;

                    IEnumerable<BookmarkStart> rs = from bm in mainPart.Document.Body.Descendants<BookmarkStart>() where bm.Name == bookMark select bm;

                    DocumentFormat.OpenXml.OpenXmlElement bookmark = rs.SingleOrDefault();

                    if (bookmark != null)
                    {
                        DocumentFormat.OpenXml.OpenXmlElement parent = bookmark.Parent;
                        AltChunk altchunk = new AltChunk();
                        string chunkId = bookMark + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
                        altchunk.Id = chunkId;
                        AlternativeFormatImportPart formatImport = doc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, chunkId);
                        formatImport.FeedData(memoryStream);
                        parent.InsertBeforeSelf(altchunk);
                    }
                }
            }
            catch (Exception ext)
            {
                throw ext;
            }
        }