How to copy a paragraph as an image

If using Interop word:

Application wordApp = new Application();
Document wordDoc = wordApp.Documents.Open("D:\\Replace2.docx");
int paragraph_start = 1;
Range rngFind = .Paragraphs[paragraph_start].Range;
                rngFind.Select();
                rngFind.CopyAsPicture();
                document.Content.PasteSpecial(DataType: WdPasteOptions.wdKeepSourceFormatting);

I want to do the same thing with Aspose Word

@quanghieumylo Unfortunately, there is no built-in method for copying paragraph as an image in Aspose.Words. However, you can achieve this by copying the paragraph into a separate document and saving it as image:

Document doc = new Document(@"C:\Temp\in.docx");

// get a paragraph.
Paragraph p = doc.FirstSection.Body.FirstParagraph;

// Copy it into a separate document.
Document tmp = (Document)doc.Clone(false);
tmp.AppendChild(tmp.ImportNode(p.GetAncestor(NodeType.Section), false));
tmp.FirstSection.EnsureMinimum();
tmp.FirstSection.Body.PrependChild(tmp.ImportNode(p, true));
// wrap paragraph with bookmark. It is required to calculate paragraph bounds.
string tmpBookmarkName = "tmp";
tmp.FirstSection.Body.FirstParagraph.PrependChild(new BookmarkStart(tmp, tmpBookmarkName));
tmp.FirstSection.Body.FirstParagraph.AppendChild(new BookmarkEnd(tmp, tmpBookmarkName));

// now use LayoutEnumerator and LayoutCollector to calculate bounds of the paragraph.
LayoutCollector collector = new LayoutCollector(tmp);
LayoutEnumerator enumerator = new LayoutEnumerator(tmp);

enumerator.Current = collector.GetEntity(tmp.FirstSection.Body.FirstParagraph.FirstChild);
while (enumerator.Type != LayoutEntityType.Line)
    enumerator.MoveParent();

RectangleF paraBounds = enumerator.Rectangle;

enumerator.Current = collector.GetEntity(tmp.FirstSection.Body.FirstParagraph.LastChild);
while (enumerator.Type != LayoutEntityType.Line)
    enumerator.MoveParent();

paraBounds = RectangleF.Union(paraBounds, enumerator.Rectangle);

// Adjust page size and margins.
PageSetup ps = tmp.FirstSection.PageSetup;
ps.LeftMargin = 0;
ps.RightMargin = 0;
ps.TopMargin = 0;
ps.BottomMargin = 0;
ps.PageWidth = paraBounds.Width;
ps.PageHeight = paraBounds.Height;

// Since we chnaged document after updating page layout, we should update it again so the chnages have effect.
tmp.UpdatePageLayout();
tmp.Save(@"C:\Temp\para.png");
2 Likes

A post was split to a new topic: Render paragraph as an image C++