Как использовать библиотеку «SautinSoft.PdfVision» под Linux


Здесь мы подготовили для Вас пошаговое руководство «Использование SautinSoft.PdfVision под Linux.pdf» (.pdf, 1.3Mb).

Preparing environment

In order to build multi-platform applications using .NET Core on Linux, the first steps are for installing in our Linux machine the required tools.

We need to install .NET Core SDK from Microsoft and to allow us to develop easier, we will install an advance editor with a lot of features, Visual Studio Code from Microsoft.

Both installations are very easy and the detailed description can be found by these two links:

  1. Install .NET Core SDK for Linux..
  2. Install VS Code for Linux..
  3. Install C# extension to facilitate us to code and debugging.

Check the installed Fonts availability

Check that the directory with fonts "/usr/share/fonts/truetype" is exist. Also check that it contains *.ttf files.

    If you don't see this folder, make these steps:
  1. Download the archive with *.ttf fonts: Fonts.tar
  2. Uncompress the downloaded font’s archive to a directory and add it to the font path, a list of directories containing fonts:# tar xvzf
  3. Create a directory for new fonts # mkdir /usr/share/fonts/truetype
  4. Move the uncompressed font files to the new font directory# mv *.ttf /usr/share/fonts/truetype
  5. Navigate to the font directory # cd /usr/share/fonts/truetype
  6. Create fonts.scale and fonts.dir # mkfontscale && mkfontdir # fc-cache
  7. Add the new font directory to the X11 font path# chkfontpath --add /usr/share/fonts/truetype
  8. Restart X font server # /etc/rc.d/init.d/xfs restart

You can verify the successful addition of the new path by running chkfontpath command or by listing X font server's /etc/X11/XF86Config file.

If you do not have root access, copy the *.ttf to ~/.fonts directory instead.

Or you may install “Microsoft TrueType core fonts” using terminal and command: $ sudo apt install ttf-mscorefonts-installer

Read more about TrueType Fonts and “How to install Microsoft fonts, How to update fonts cache files, How to confirm new fonts installation” .

With these steps, we will ready to start developing.

In next paragraphs we will explain in detail how to create simple console application. All of them are based on this VS Code guide:

Get Started with C# and Visual Studio Code

Not only is possible to create .NET Core applications that will run on Linux using Linux as a developing platform. It is also possible to create it using a Windows machine and any modern Visual Studio version, as Microsoft Visual Studio Community 2022.

Creating “Convert HTML to PDF” application

Create a new folder in your Linux machine with the name HTML to PDF.

For example, let’s create the folder “HTML to PDF” on Desktop ( Right click-> New Folder):

Open VS Code and click in the menu File->Open Folder. From the dialog, open the folder you’ve created previously:

Next you will see the similar screen:

Now, open the integrated console – the Terminal: follow to the menu Terminal -> New

Terminal (or press Ctrl+Shift+’):

Create a new console application, using dotnet command.

Type this command in the Terminal console: dotnet new console

Now we are going to convert this simple application into something more interesting. We’ll transform it into an application that will convert a HTML to PDF.

First of all, we need to add the package reference to the sautinsoft.pdfvision assembly using Nuget.

In order to do it, follow to the Explorer and open project file “HTML to PDF.csproj” within

VS Code to edit it:

Add these lines into the HTML to PDF.csproj file:

<ItemGroup>
<PackageReference Include="sautinsoft.pdfvision" Version="*" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.7" />
</ItemGroup>

The first reference installs the latest version sautinsoft.pdfvision package from Nuget.

The second reference installs the SkiaSharp.NativeAssets.Linux package, which adds 2D graphics to .Net applications for Linux.

At once as we’ve added the package reference, we have to save the “HTML to PDF.csproj” and restore the added package.

Follow to the Terminal and type the command: dotnet restore

Good, now our application has the reference to sautinsoft.pdfvision package and we can write the code to convert HTML to PDF and other formats.

Follow to the Explorer, open the Program.cs, remove all the code and type the new:

using SautinSoft.PdfVision;

namespace HTML_to_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Before starting, we recommend to get a free 100-day key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // SautinSoft.PdfVision.SetLicense("...");
            string inpFile = "/home/alex/Desktop/Sample.html";
            string outFile = "/home/alex/Desktop/Result.pdf";

            // Local chromium will be downloaded into this directory.
            // This takes time only at the first startup.
            string chromiumDirectory = Path.GetFullPath(@"/home/alex/Desktop/Chromium/");

            PdfVision v = new PdfVision();

            HtmlToPdfOptions options = new HtmlToPdfOptions()
            {
                PageSetup = new PageSetup()
                {
                    PaperType = PaperType.Letter,
                    Orientation = Orientation.Portrait,
                    PageMargins = new PageMargins()
                    {
                        Left = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
                        Top = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
                        Right = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
                        Bottom = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter)
                    }
                },
                ChromiumBaseDirectory = chromiumDirectory
            };

            try
            {
                v.ConvertHtmlToPdf(inpFile, outFile, options);
                // Open the result for demonstration purposes.
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.ReadLine();
            }
        }
    }
}

To make tests, we need an input HTML document. For our tests, let’s place a HTML file with the name “sample.html” at the Desktop.

If we open this file, well its contents:

Launch our application and convert the “sample.html” into “sample.pdf”, type the

command: dotnet run

If you don’t see any exceptions, everything is fine, and we can check the result produced by the SautinSoft.PdfVision library.

The new file “sample.pdf” has to appear on the Desktop:

Open the result:

Well done! You have created the “HTML to PDF” application under Linux!

If you have any troubles or need extra code, or help, don’t hesitate to ask our SautinSoft

Team at support@sautinsoft.com.


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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