Exemplo n.º 1
0
        /// <summary>
        /// Настройка страницы и колонтитул на 1 странице
        /// </summary>
        /// <param name="body"></param>
        /// <param name="mainDocument"></param>
        public void SettingPage(ref Body body, MainDocumentPart mainDocument)
        {
            SectionProperties sectionProperties = new SectionProperties();
            PageSize          pageSize          = new PageSize()
            {
                Width = 11900U, Height = 16840U
            };
            PageMargin pageMargin = new PageMargin()
            {
                Top = 1440, Right = 700U, Bottom = -1400, Left = 1470U, Header = 710U, Footer = 700U, Gutter = 0U
            };
            TitlePage titlePage = new TitlePage();

            sectionProperties.Append(pageSize);
            sectionProperties.Append(pageMargin);
            sectionProperties.Append(titlePage);
            sectionProperties.Append(new FooterReference()
            {
                Type = HeaderFooterValues.Default, Id = mainDocument.GetIdOfPart(mainDocument.FooterParts.FirstOrDefault())
            });
            sectionProperties.Append(new FooterReference()
            {
                Type = HeaderFooterValues.First, Id = mainDocument.GetIdOfPart(mainDocument.FooterParts.FirstOrDefault())
            });
            body.Append(sectionProperties);
        }
Exemplo n.º 2
0
        //private void OpenHeaderFooter(OXmlOpenHeaderFooter element)
        //{
        //    CreateSectionProperties();
        //    OpenXmlCompositeElement headerFooter;
        //    if (element.Header)
        //    {
        //        HeaderPart headerPart = _mainPart.AddNewPart<HeaderPart>();
        //        headerFooter = new Header();
        //        headerPart.Header = (Header)headerFooter;
        //        string headerPartId = _mainPart.GetIdOfPart(headerPart);
        //        _sectionProperties.AppendChild(new HeaderReference { Id = headerPartId, Type = element.HeaderType });
        //    }
        //    else
        //    {
        //        FooterPart footerPart = _mainPart.AddNewPart<FooterPart>();
        //        headerFooter = new Footer();
        //        footerPart.Footer = (Footer)headerFooter;
        //        string footerPartId = _mainPart.GetIdOfPart(footerPart);
        //        _sectionProperties.AppendChild(new FooterReference { Id = footerPartId, Type = element.HeaderType });
        //    }
        //    AddHeaderFooterNamespaceDeclaration((OpenXmlPartRootElement)headerFooter);

        //    SetHeaderFooterProperties(element.HeaderType);

        //    _element = headerFooter;
        //    _headerFooter = true;
        //}

        private void OpenHeader(OXmlOpenHeaderElement element)
        {
            CreateSectionProperties();
            //if (element.Header)
            //{
            HeaderPart headerPart          = _mainPart.AddNewPart <HeaderPart>();
            OpenXmlCompositeElement header = new Header();

            headerPart.Header = (Header)header;
            string headerPartId = _mainPart.GetIdOfPart(headerPart);

            _sectionProperties.AppendChild(new HeaderReference {
                Id = headerPartId, Type = element.HeaderType
            });
            //}
            //else
            //{
            //    FooterPart footerPart = _mainPart.AddNewPart<FooterPart>();
            //    headerFooter = new Footer();
            //    footerPart.Footer = (Footer)headerFooter;
            //    string footerPartId = _mainPart.GetIdOfPart(footerPart);
            //    _sectionProperties.AppendChild(new FooterReference { Id = footerPartId, Type = element.HeaderType });
            //}
            AddHeaderFooterNamespaceDeclaration((OpenXmlPartRootElement)header);

            SetHeaderFooterProperties(element.HeaderType);

            _element = header;
            //_headerFooter = true;
            _currentElement = OXmlDocElementType.Header;
        }
        /// <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);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Add an image to the body by its stream
        /// </summary>
        /// <param name="image"></param>
        public void AddImage(Stream image)
        {
            ImagePart imagePart = _mainDocumentPart.AddImagePart("image/png");

            imagePart.FeedData(image);
            AddImageToBody(_package, _mainDocumentPart.GetIdOfPart(imagePart));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Download the image and try to find its format type.
        /// </summary>
        private HtmlImageInfo DownloadRemoteImage(string src)
        {
            Uri      imageUri = new Uri(src, UriKind.RelativeOrAbsolute);
            Resource response;

            try
            {
                response = resourceLoader.FetchAsync(imageUri, CancellationToken.None).Result;
                if (response?.Content == null)
                {
                    return(null);
                }
            }
            catch (Exception exc)
            {
                if (Logging.On)
                {
                    Logging.PrintError(String.Format("Error fetching image from url: {0}", src), exc);
                }
                return(null);
            }

            HtmlImageInfo info = new HtmlImageInfo()
            {
                Source = src
            };
            ImagePartType type;

            using (response)
            {
                // For requested url with no filename, we need to read the media mime type if provided
                response.Headers.TryGetValue("Content-Type", out string mime);
                if (!TryInspectMimeType(mime, out type) &&
                    !TryGuessTypeFromUri(imageUri, out type) &&
                    !TryGuessTypeFromStream(response.Content, out type))
                {
                    return(null);
                }

                var ipart = mainPart.AddImagePart(type);
                using (var outputStream = ipart.GetStream(FileMode.Create))
                {
                    response.Content.CopyTo(outputStream);

                    outputStream.Seek(0L, SeekOrigin.Begin);
                    info.Size = GetImageSize(outputStream);
                }

                info.ImagePartId = mainPart.GetIdOfPart(ipart);
                return(info);
            }
        }
Exemplo n.º 6
0
        //word doc add image, and convert image to text
        public static void DocxAddImage(MainDocumentPart mainPart, ref string text, List <WordImageDto> images)
        {
            if (images == null || images.Count == 0)
            {
                return;
            }

            foreach (var image in images)
            {
                //var imagePath = images[i];
                //var width = Convert.ToDouble(images[i + 1]);
                //var height = Convert.ToDouble(images[i + 2]);
                //var tag = images[i + 3];
                var imageService = new WordImageService(image.FilePath, image.Width, image.Height);
                var newText      = "";
                if (imageService.DataStream != null)
                {
                    //TODO: how multiple images ??
                    var imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
                    imagePart.FeedData(imageService.DataStream);
                    var imagePartId = mainPart.GetIdOfPart(imagePart);
                    newText = GetImageRun(imagePartId, imageService).InnerXml;
                }

                text.Replace(image.Tag, newText);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 按书签插入图片
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="picPath"></param>
        /// <param name="bm"></param>
        /// <param name="x">宽度厘米</param>
        /// <param name="y">高度厘米</param>
        /// <param name="type"></param>
        public static void InsertBMPicture(string filePath, string picPath, string bm, long x, long y, ImagePartType type)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;

                BookmarkStart bmStart = findBookMarkStart(doc, bm);
                if (bmStart == null)
                {
                    return;
                }

                ImagePart imagePart = mainPart.AddImagePart(type);

                using (FileStream stream = new FileStream(picPath, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }
                long cx = 360000L * x;//360000L = 1厘米
                long cy = 360000L * y;
                Run  r  = AddImageToBody(doc, mainPart.GetIdOfPart(imagePart), cx, cy);
                bmStart.Parent.InsertAfter <Run>(r, bmStart);
                mainPart.Document.Save();
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Настройки параграфа с разрывом
        /// </summary>
        /// <param name="body"></param>
        /// <param name="mainDocument"></param>
        public void SettingParagraph(ref Body body, MainDocumentPart mainDocument)
        {
            Paragraph           paragraph           = new Paragraph();
            ParagraphProperties paragraphProperties = new ParagraphProperties();

            SectionProperties sectionProperties = new SectionProperties();
            FooterReference   footerReference   = new FooterReference()
            {
                Type = HeaderFooterValues.Default, Id = mainDocument.GetIdOfPart(mainDocument.FooterParts.FirstOrDefault())
            };
            SectionType sectionType = new SectionType()
            {
                Val = SectionMarkValues.Continuous
            };
            PageMargin pageMargin = new PageMargin()
            {
                Top = 1440, Right = 700U, Bottom = -1400, Left = 1470U, Header = 710U, Footer = 700U, Gutter = 0U
            };

            sectionProperties.Append(footerReference);
            sectionProperties.Append(sectionType);
            sectionProperties.Append(pageMargin);
            paragraphProperties.Append(sectionProperties);
            paragraph.Append(paragraphProperties);
            body.Append(paragraph);
        }
Exemplo n.º 9
0
    public static ImageInfo Create(MainDocumentPart documentPart, ImagePart image)
    {
        String    id = documentPart.GetIdOfPart(image);
        ImageInfo r  = new ImageInfo(image, id);

        return(r);
    }
Exemplo n.º 10
0
        //gavdcodeend 11

        //gavdcodebegin 12
        public static void WordOpenXmlCreateFooter()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                MainDocumentPart docMainPart = myWordDoc.MainDocumentPart;

                docMainPart.DeleteParts(docMainPart.FooterParts);
                FooterPart defaultFooterPart = docMainPart.AddNewPart <FooterPart>();

                GenerateFooterPartContent(defaultFooterPart);

                string defaultFooterPartId = docMainPart.GetIdOfPart(defaultFooterPart);

                IEnumerable <SectionProperties> allSections =
                    docMainPart.Document.Body.Elements <SectionProperties>();

                foreach (var oneSection in allSections)
                {
                    oneSection.RemoveAllChildren <FooterReference>();
                    oneSection.RemoveAllChildren <TitlePage>();

                    oneSection.PrependChild <FooterReference>(new FooterReference()
                    {
                        Id = defaultFooterPartId, Type = HeaderFooterValues.Default
                    });
                    oneSection.PrependChild <TitlePage>(new TitlePage());
                }
                docMainPart.Document.Save();
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Render the header of document
        /// </summary>
        /// <param name="footer"></param>
        /// <param name="document"></param>
        /// <param name="mainDocumentPart"></param>
        /// <param name="context"></param>
        /// <param name="formatProvider"></param>
        public static void Render(this Models.Footer footer, Models.Document document, MainDocumentPart mainDocumentPart, ContextModel context, IFormatProvider formatProvider)
        {
            var footerPart = mainDocumentPart.AddNewPart <FooterPart>();

            footerPart.Footer = new Footer();

            foreach (var element in footer.ChildElements)
            {
                element.InheritFromParent(footer);
                element.Render(document, footerPart.Footer, context, footerPart, formatProvider);
            }

            string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);

            if (!mainDocumentPart.Document.Body.Descendants <SectionProperties>().Any())
            {
                mainDocumentPart.Document.Body.AppendChild(new SectionProperties());
            }
            foreach (var section in mainDocumentPart.Document.Body.Descendants <SectionProperties>())
            {
                section.PrependChild(new FooterReference()
                {
                    Id = footerPartId, Type = (DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues)(int) footer.Type
                });
            }

            if (footer.Type == HeaderFooterValues.First)
            {
                mainDocumentPart.Document.Body.Descendants <SectionProperties>().First().PrependChild(new TitlePage());
            }
        }
Exemplo n.º 12
0
        private static Paragraph InsertImage(MainDocumentPart mainPart, string imagePath)
        {
            var extension = Path.GetExtension(imagePath);
            var imagePart = AddImagePart(mainPart, extension);

            byte[] imageBytes;
            using (var webClient = new WebClient())
            {
                imageBytes = webClient.DownloadData(imagePath);
            }

            long widthEmus;
            long heightEmus;

            using (var stream = new MemoryStream(imageBytes))
            {
                var image = Image.FromStream(stream);
                SetImageDimensions(image, out widthEmus, out heightEmus);
            }

            using (var stream = new MemoryStream(imageBytes))
            {
                imagePart.FeedData(stream);
            }

            var idOfPart  = mainPart.GetIdOfPart(imagePart);
            var paragraph = CreateImageParagraph(idOfPart, widthEmus, heightEmus);

            return(paragraph);
        }
Exemplo n.º 13
0
        public static void InsertAPicture(string fileName, string document, string bookmark)
        {
            OpenSettings openSettings = new OpenSettings();

            // Add the MarkupCompatibilityProcessSettings
            openSettings.MarkupCompatibilityProcessSettings =
                new MarkupCompatibilityProcessSettings(
                    MarkupCompatibilityProcessMode.ProcessAllParts,
                    FileFormatVersions.Office2007);

            //   string document = @"E:\**项目\**文书\108.docx";
            //   document = @"F:\Project_Code\SVNProject\SDHS_SZCG_ZCCG\SZZF\SZZFWord\xcjckyyszj.docx";
            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Open(document, true))
            {
                MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                using (FileStream stream = new FileStream(fileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }



                AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), bookmark);
            }
        }
Exemplo n.º 14
0
        private void ImagenHeader(string imgRuta, MainDocumentPart documento, WordprocessingDocument documentoWord)
        {
            if (!documento.HeaderParts.Any())
            {
                documento.DeleteParts(documento.HeaderParts);
                var newHeaderPart = documento.AddNewPart <HeaderPart>();

                var imgPart     = newHeaderPart.AddImagePart(ImagePartType.Jpeg, "rId999");
                var imagePartID = newHeaderPart.GetIdOfPart(imgPart);

                using (FileStream fs = new FileStream(fileName, FileMode.Open))
                {
                    imgPart.FeedData(fs);
                }
                var rId       = documento.GetIdOfPart(newHeaderPart);
                var headerRef = new HeaderReference {
                    Id = rId
                };
                var sectionProps = documentoWord.MainDocumentPart.Document.Body.Elements <SectionProperties>().LastOrDefault();
                if (sectionProps == null)
                {
                    sectionProps = new SectionProperties();
                    documentoWord.MainDocumentPart.Document.Body.Append(sectionProps);
                }
                sectionProps.RemoveAllChildren <HeaderReference>();
                sectionProps.Append(headerRef);
                newHeaderPart.Header = GenerarImagenHeaeder(imagePartID);
                newHeaderPart.Header.Save();
            }
        }
Exemplo n.º 15
0
        public static void ExportCaseToDoc(Case caseFile, string mapImagePath, string folderName)
        {
            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Create(Path.Combine(folderName, string.Format("CaseReport-{0}.docx", caseFile.CaseNumber)), WordprocessingDocumentType.Document))
            {
                //wordprocessingDocument.AddMainDocumentPart();

                MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                var  para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                var  run  = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());

                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(string.Format("GPS Coordinate Report: Case #{0}", caseFile.CaseNumber)));
                ApplyStyleToParagraph(wordprocessingDocument, "Title", "Title", para);
                AddTable(body, caseFile.GPSCoordinates.Where(g => g.IncludedInMap).OrderBy(g => g.FileTime).ToList());
                using (FileStream fs = new FileStream(mapImagePath, FileMode.Open, FileAccess.Read))
                {
                    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
                    imagePart.FeedData(fs);
                    AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
                }

                //wordprocessingDocument.Save();
                wordprocessingDocument.Close();
            }
        }
Exemplo n.º 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();
                }
            }
        }
Exemplo n.º 17
0
        private Run AddImage(WordprocessingDocument wordprocessingDocument, OpenXmlElement refChild, string imageBase64)
        {
            var bytes     = Convert.FromBase64String(imageBase64.Split(',')[1]);
            var imagePath = Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";

            try
            {
                MainDocumentPart mainPart  = wordprocessingDocument.MainDocumentPart;
                ImagePart        imagePart = mainPart.AddImagePart(ImagePartType.Png);

                File.WriteAllBytes(imagePath, bytes);



                // Carregando a imagem em imagePart
                using (FileStream stream = new FileStream(imagePath, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }
                return(AddImageToBody(wordprocessingDocument, refChild, mainPart.GetIdOfPart(imagePart), imagePath));
            }
            finally
            {
                File.Delete(imagePath);
            }
        }
Exemplo n.º 18
0
        public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart)
        {
            _mainDocumentPart = mainDocumentPart;

            var imagePart = CreateImagePart();

            openXmlNode.Append(CreateImageElement(mainDocumentPart.GetIdOfPart(imagePart), Path.GetFileName(_content)));
        }
Exemplo n.º 19
0
        public override void InsertAfter(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart)
        {
            _mainDocumentPart = mainDocumentPart;

            var imagePart = CreateImagePart();

            openXmlNode.InsertAfterSelf(CreateImageElement(mainDocumentPart.GetIdOfPart(imagePart), Path.GetFileName(_content)));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Adds an image part to the document and returns the part ID
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        protected override string AddImagePart(Stream stream, string contentType)
        {
            var imagePart = MainDocumentPart.AddImagePart(ImagePartType.Png);

            imagePart.FeedData(stream);

            return(MainDocumentPart.GetIdOfPart(imagePart));
        }
Exemplo n.º 21
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);
                }
            }
        }
Exemplo n.º 22
0
        public static void ChangeHeader(String documentPath)
        {
            // Replace header in target document with header of source document.
            using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true))
            {
                // Get the main document part
                MainDocumentPart mainDocumentPart = document.MainDocumentPart;

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

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

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

                GenerateHeaderPartContent(headerPart);

                GenerateFooterPartContent(footerPart);

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

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

                    // Create the new header and footer reference node
                    section.PrependChild <HeaderReference>(new HeaderReference()
                    {
                        Id = headerPartId
                    });
                    section.PrependChild <FooterReference>(new FooterReference()
                    {
                        Id = footerPartId
                    });
                }
            }
        }
Exemplo n.º 23
0
        public static void CreateWordprocessingDocument(string filepath, List <Student> st)
        {
            String fileName = Constants.Locations.ImagesFolder + "/" + Constants.Locations.ImageFile;

            using (WordprocessingDocument wordDocument =
                       WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part.
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                // Create the document structure and add some text.
                mainPart.Document = new Document();

                Body body = mainPart.Document.AppendChild(new Body());



                foreach (var stu in st)
                {
                    Paragraph para = body.AppendChild(new Paragraph());


                    Run run = para.AppendChild(new Run());
                    run.AppendChild(new Text("Hello , my name is " + stu.FirstName + " " + stu.LastName + "\n\n"));



                    string imageFilePath = stu.FullPathUrl + "/" + Constants.Locations.ImageFile;


                    var ImageBytes = FTP.DownloadFileBytes(imageFilePath);

                    SaveBytesToFile(fileName, ImageBytes);


                    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                    using (FileStream stream = new FileStream(fileName, FileMode.Open))
                    {
                        imagePart.FeedData(stream);
                    }


                    AddImageToBody(wordDocument, mainPart.GetIdOfPart(imagePart));

                    Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break()
                    {
                        Type = BreakValues.Page
                    }));


                    body.Append(PageBreakParagraph);
                }

                // var styles = ExtractStylesPart(filepath, true);
            }
        }
        //word插入图片
        public static void InsertAPicture(string document, string fileName)
        {
            string imgType = fileName.Split('.')[fileName.Split('.').Length - 1];

            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Open(document, true))
            {
                try
                {
                    MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

                    ImagePart imagePart = null;
                    //判断图片的格式
                    if (imgType.ToUpper() == "JPEG" || imgType.ToUpper() == "JPE")
                    {
                        imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
                    }
                    else if (imgType.ToUpper() == "PNG")
                    {
                        imagePart = mainPart.AddImagePart(ImagePartType.Png);
                    }
                    else if (imgType.ToUpper() == "GIF")
                    {
                        imagePart = mainPart.AddImagePart(ImagePartType.Gif);
                    }
                    else if (imgType.ToUpper() == "TIFF" || imgType.ToUpper() == "TIF")
                    {
                        imagePart = mainPart.AddImagePart(ImagePartType.Tiff);
                    }

                    if (imagePart != null)
                    {
                        if (File.Exists(fileName))
                        {
                            using (FileStream stream = new FileStream(fileName, FileMode.Open))
                            {
                                imagePart.FeedData(stream);
                            }

                            AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
                        }
                        else
                        {
                            Console.WriteLine("图片文件不存在");
                        }
                    }
                    else
                    {
                        Console.WriteLine("不支持的图片类型");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("文档被占用!" + e);
                }
            }
        }
Exemplo n.º 25
0
        public static void InsertPicture(string fullPathToImageFile, WordprocessingDocument wordDoc)
        {
            MainDocumentPart mainPart  = wordDoc.MainDocumentPart;
            ImagePart        imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

            using (FileStream stream = new FileStream(fullPathToImageFile, FileMode.Open)) {
                imagePart.FeedData(stream);
            }
            AddImageToBody(wordDoc, mainPart.GetIdOfPart(imagePart));
        }
Exemplo n.º 26
0
    public void Reparent(MainDocumentPart documentPart)
    {
        ImagePart newImage = documentPart.AddImagePart(this._image.ContentType);

        newImage.FeedData(this._image.GetStream(FileMode.Open, FileAccess.Read));
        String newId = documentPart.GetIdOfPart(newImage);

        this._id    = newId;
        this._image = newImage;
    }
        /// <summary>
        /// Копирует в <paramref name="weekDoc"/> объекты, на которые ссылается шаблон дня
        /// </summary>
        /// <param name="weekDoc"></param>
        /// <param name="modDayTemplate"></param>
        private void CopyRelativeElements(WordprocessingDocument weekDoc, MainDocumentPart documentPart, IEnumerable <OpenXmlElement> elements)
        {
            foreach (var oldPart in documentPart.ImageParts)
            {
                var newPart = weekDoc.MainDocumentPart.AddImagePart(oldPart.ContentType);
                newPart.FeedData(oldPart.GetStream(FileMode.Open, FileAccess.Read));

                ReplaceRelationShips(elements, documentPart.GetIdOfPart(oldPart), weekDoc.MainDocumentPart.GetIdOfPart(newPart));
            }
        }
Exemplo n.º 28
0
        private void InsertPicturePng(Stream imageStream, double scaleWidth, double scaleHeight)
        {
            MainDocumentPart mainPart = WordDoc.MainDocumentPart;

            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);

            imagePart.FeedData(imageStream);

            AddImageToBody(mainPart.GetIdOfPart(imagePart), scaleWidth, scaleHeight);
        }
        public void InsertPicture(WordprocessingDocument wordprocessingDocument, string fileName)
        {
            MainDocumentPart mainPart  = wordprocessingDocument.MainDocumentPart;
            ImagePart        imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }
            AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
        }
Exemplo n.º 30
0
        private static SectionProperties GetFooterSectionProperties(MainDocumentPart mainPart, out FooterPart fp, out SectionProperties sectPr)
        {
            fp = mainPart.AddNewPart <FooterPart>();
            string relId = mainPart.GetIdOfPart(fp);

            sectPr = new SectionProperties();
            FooterReference footerReference = new FooterReference();

            footerReference.Id = relId;
            sectPr.Append(footerReference);
            return(sectPr);
        }