Вставка элемента управления содержимым изображения в C# и .NET


    Заполняет элемент управления содержимым одним изображением. Запрещает пользователям вставлять любые другие объекты Word или любой текст.

Полный код

using System;
using System.Threading.Tasks;
using SautinSoft.Document;
using SautinSoft.Document.CustomMarkups;
using SautinSoft.Document.Drawing;
using SautinSoft.Document.Tables;
using System.Net;
using System.IO;


namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/

            InsertPicture();
        }
        /// <summary>
        /// Inserting a Picture content control.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/content-controls-insert-picture-net-csharp-vb.php
        /// </remarks>

        static void InsertPicture()
        {
            // Let's create a simple document.
            DocumentCore dc = new DocumentCore();
            Picture pict, pict1, pict2;

            byte[] imageBytes = File.ReadAllBytes(@"..\..\..\banner_sautinsoft.jpg");
            using (MemoryStream ms = new MemoryStream(imageBytes))
            {
                pict = new Picture(dc, new InlineLayout(new Size(400, 100)), ms);
            }

            imageBytes = File.ReadAllBytes(@"..\..\..\developer.png");
            using (MemoryStream ms = new MemoryStream(imageBytes))
            {
                pict1 = new Picture(dc, new InlineLayout(new Size(50, 50)), ms);
            }

            Section section = new Section(dc);
            dc.Sections.Add(section);

            section.Blocks.Add(new Paragraph(dc, "Picture below is inside the block-level content control:"));

            // Create a picture content control.
            BlockContentControl control = new BlockContentControl(dc, ContentControlType.Picture, new Paragraph(dc, pict));
            section.Blocks.Add(control);

            Paragraph par = new Paragraph(dc,
                new Run(dc, "Following picture is inside the inline-level content control: "),
                new InlineContentControl(dc, ContentControlType.Picture, pict1));
            section.Blocks.Add(par);

            section.Blocks.Add(new Paragraph(dc, "Insert a picture content control from the local disk:"));
            string pictPath = @"..\..\..\picture.jpg";
            pict2 = new Picture(dc, new InlineLayout(new Size(100, 100)), pictPath);
            BlockContentControl localpict = new BlockContentControl(dc, ContentControlType.Picture, new Paragraph(dc, pict2));
            section.Blocks.Add(localpict);

            // Save our document into DOCX format.
            string resultPath = @"result.docx";
            dc.Save(resultPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On
Imports System.Threading.Tasks
Imports SautinSoft.Document
Imports SautinSoft.Document.CustomMarkups
Imports SautinSoft.Document.Drawing
Imports SautinSoft.Document.Tables
Imports System.Net
Imports System.Net.Http
Imports System.IO



Namespace Example
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            InsertPicture()
        End Sub
        ''' Get your free 100-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Inserting a Picture content control.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/content-controls-insert-picture-net-csharp-vb.php
        ''' </remarks>

        Private Shared Sub InsertPicture()
            ' Let's create a simple document.
            Dim dc As New DocumentCore()
            Dim pict, pict1, pict2 As Picture

            Dim imageBytes() As Byte = File.ReadAllBytes("..\..\..\banner_sautinsoft.jpg")
            Using ms As New MemoryStream(imageBytes)
                pict = New Picture(dc, New InlineLayout(New Size(400, 100)), ms)
            End Using

            imageBytes = File.ReadAllBytes("..\..\..\developer.png")
            Using ms As New MemoryStream(imageBytes)
                pict1 = New Picture(dc, New InlineLayout(New Size(50, 50)), ms)
            End Using

            Dim section As New Section(dc)
            dc.Sections.Add(section)

            section.Blocks.Add(New Paragraph(dc, "Picture below is inside the block-level content control:"))

            ' Create a picture content control.
            Dim control As New BlockContentControl(dc, ContentControlType.Picture, New Paragraph(dc, pict))
            section.Blocks.Add(control)

            Dim par As New Paragraph(dc, New Run(dc, "Following picture is inside the inline-level content control: "), New InlineContentControl(dc, ContentControlType.Picture, pict1))
            section.Blocks.Add(par)

            section.Blocks.Add(New Paragraph(dc, "Insert a picture content control from the local disk:"))
            Dim pictPath As String = "..\..\..\picture.jpg"
            pict2 = New Picture(dc, New InlineLayout(New Size(100, 100)), pictPath)
            Dim localpict As New BlockContentControl(dc, ContentControlType.Picture, New Paragraph(dc, pict2))
            section.Blocks.Add(localpict)

            ' Save our document into DOCX format.
            Dim resultPath As String = "result.docx"
            dc.Save(resultPath)

            ' Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(resultPath) With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.