MVC C# HTML to PDF with Watermark

ASPOSE examples do not show how to create a PDF with a watermark from a HTML file. Please provide example that will handle this plus have the watermark added in memory, not create pdf then add watermark to pdf. The ASPOSE document “Customizing Watermark and Writing PDF directly” when copied into Visual Studio 2015 causes error, “Generator does not exist in Aspose.Pdf” the Aspose.Pdf file is referenced, it is version 17.8.0.0

@LoganJH,
Please try the following code:

[C#]

string dataDir = @"C:\Pdf\test262\";
ArrayList watermark = new ArrayList();
watermark.Add("Test Line 1");
watermark.Add("Test Line 2");
watermark.Add("Test Line 3");

// import an HTML document
Aspose.Pdf.HtmlLoadOptions options = new Aspose.Pdf.HtmlLoadOptions();
Document pdfDocument = new Document(dataDir + "HTML.html", options);
pdfDocument.Pages.Add();
ArrayList textStamps = new ArrayList();

// arrange multiline text stamp text
FormattedText ft = new FormattedText(watermark[0].ToString(), System.Drawing.Color.LightGray, "Helvetica", EncodingType.Winansi, false, 80);
for (int i = 1; i < watermark.Count; i++)
    ft.AddNewLineText(watermark[i].ToString());

TextStamp stamp = new TextStamp(ft);
stamp.Background = true;
stamp.Opacity = 0.5;
stamp.RotateAngle = -45;
stamp.TextAlignment = HorizontalAlignment.Center;
stamp.HorizontalAlignment = HorizontalAlignment.Center;
stamp.VerticalAlignment = VerticalAlignment.Center;

// add stamp to page collection
pdfDocument.Pages[1].AddStamp(stamp);
pdfDocument.Save(dataDir + "test.pdf"); 

These are the HTML and PDF documents: HTML.zip (237 Bytes) and test.pdf (31.8 KB)

This is a MVC project, so directly linking the html file won’t work. The model needs to be sent to the MVC page. When I use your code all my objects show “@Model.customer.FirstName @Model.customer.LastName

How do I send a MVC view into pdf with a watermark?

@LoganJH,
We are working over your query and will get back to you soon.

@LoganJH,
You can convert MVC view to HTML string. Please try the following code:

C#

public ActionResult About()
{
//ViewBag. Message = “Your application description page.”;

//return View();
var model = new EmailConfirmationModel()
{
    FirstName = "John",
    LastName = "Doe",
    InvoiceNo = "DoeBoy1",
    Email = "abc@abcOutlet.com",
    OrderTotal = 299.33M,
    ItemSku = "ABCHELP",
    ItemDescription = "Html Help Builder",
    StoreName = "ABC Store"
};
string html = ViewRenderer.RenderView("~/Views/Home/About.cshtml", model);

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(html);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);

// import an HTML document
Aspose.Pdf.HtmlLoadOptions options = new Aspose.Pdf.HtmlLoadOptions();
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(stream, options);
        
// process further to add watermark etc.
// save Pdf        
return View();

}

These are the required files: CodeFiles.zip (2.9 KB)

I added your code to my project and now the watermark shows HOWEVER all my images are missing.

Also instead of return View() I want to send the pdf file to the user, like return pdfDocument, how do I do that?

@LoganJH,
You can return a FileResult or FileStreamResult from your action. Aspose.Pdf for .NET API allows to save the output PDF into the memory stream.

C#

public ActionResult GetPdf()
{
    MemoryStream stream = new MemoryStream();
    pdfDocument.Save(stream, Aspose.Pdf.SaveFormat.Pdf);
    return File(stream.ToArray(), "application/pdf", "Outputfile.pdf");
}

Please refer to this help topic: Download PDF in the MVC project

Kindly send the complete details of the use case, including source PDF and code which you are using to manipulate a PDF document. We will investigate and share our findings with you.

I added the ASPOSE temp license and now get error that it can’t find the file. I put the file in the controllers folder.

                Aspose.Pdf.License license = new Aspose.Pdf.License();
                license.SetLicense("Aspose.Pdf.lic");
                string html = ViewRenderer.RenderView("~/Views/Home/GeneratePDF.cshtml", Session["viewModel"]);

                // convert string to stream
                byte[] byteArray = Encoding.UTF8.GetBytes(html);
                //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
                MemoryStream stream = new MemoryStream(byteArray);

                // import an HTML document
                Aspose.Pdf.HtmlLoadOptions options = new Aspose.Pdf.HtmlLoadOptions();
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(stream, options);
                pdfDocument.Pages.Add();

                ArrayList watermark = new ArrayList();
                watermark.Add("UNOFFICIAL");
                watermark.Add("UNOFFICIAL");
                watermark.Add("UNOFFICIAL");

                // arrange multiline text stamp text
                FormattedText ft = new FormattedText(watermark[0].ToString(), System.Drawing.Color.LightGray, "Helvetica", EncodingType.Winansi, false, 80);
                for (int i = 1; i < watermark.Count; i++)
                    ft.AddNewLineText(watermark[i].ToString());

                TextStamp stamp = new TextStamp(ft);
                stamp.Background = true;
                stamp.Opacity = 0.5;
                stamp.RotateAngle = -45;
                stamp.TextAlignment = HorizontalAlignment.Center;
                stamp.HorizontalAlignment = HorizontalAlignment.Center;
                stamp.VerticalAlignment = VerticalAlignment.Center;

                // add stamp to page collection
                pdfDocument.Pages[1].AddStamp(stamp);

                MemoryStream stream2 = new MemoryStream();
                pdfDocument.Save(stream2, Aspose.Pdf.SaveFormat.Pdf);
                return File(stream2.ToArray(), "application/pdf", "Outputfile.pdf");

@LoganJH,

Kindly place the license file in the same folder where you have placed Aspose.Pdf for .NET library or give a complete path like:

C#

license.SetLicense(@“c:\temp\Aspose.Pdf.lic”);

I used NuGet Package Manager and searched for Aspose.Pdf, then installed it. So Visual Studio put the file Aspose.Pdf in MyProject\packages\Aspose.Pdf.17.8\lib\net2.0 and MyProject\packages\Aspose.Pdf.17.8\lib\net40-client

So what do I do now? Do I copy the license file in both those package folders?

@LoganJH,
You can also find Aspose.Pdf library in the bin directory of the Web project, and you need to put license along with this library. Please note, there are various ways to apply license and we would recommend you please go through these help topics: Apply License to Aspose.Pdf for .NET API and Protect Aspose License Fie

ASPOSE temp license now works. Thank you.
The image is still not showing up. When I run my code without the ASPOSE code (show below) I see the image in the view with no watermark, when I run my code with the ASPOSE code I don’t see the image in the pdf but I do see the watermark.

// ASPOSE
Aspose.Pdf.License license = new Aspose.Pdf.License();
license.SetLicense(“Aspose.Pdf.lic”);
string html = ViewRenderer.RenderView("~/Views/Home/GeneratePDF-ASPOSE.cshtml", Session[“viewModel”]);

                // convert string to stream
                byte[] byteArray = Encoding.UTF8.GetBytes(html);
                //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
                MemoryStream stream = new MemoryStream(byteArray);

                // import an HTML document
                Aspose.Pdf.HtmlLoadOptions options = new Aspose.Pdf.HtmlLoadOptions();
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(stream, options);
                pdfDocument.Pages.Add();

                ArrayList watermark = new ArrayList();
                watermark.Add("UNOFFICIAL");
                watermark.Add("UNOFFICIAL");
                watermark.Add("UNOFFICIAL");

                // arrange multiline text stamp text
                FormattedText ft = new FormattedText(watermark[0].ToString(), System.Drawing.Color.LightGray, "Helvetica", EncodingType.Winansi, false, 80);
                for (int i = 1; i < watermark.Count; i++)
                    ft.AddNewLineText(watermark[i].ToString());

                TextStamp stamp = new TextStamp(ft);
                stamp.Background = true;
                stamp.Opacity = 0.5;
                stamp.RotateAngle = -45;
                stamp.TextAlignment = HorizontalAlignment.Left;
                stamp.HorizontalAlignment = HorizontalAlignment.Left;
                //stamp.VerticalAlignment = VerticalAlignment.Center;

                // add stamp to page collection
                pdfDocument.Pages[1].AddStamp(stamp);

                MemoryStream stream2 = new MemoryStream();
                pdfDocument.Save(stream2, Aspose.Pdf.SaveFormat.Pdf);
                return File(stream2.ToArray(), "application/pdf", "Outputfile.pdf");

here is the view

@model myProject.Models.myViewModel

@{
Layout = null;
}

test body, ul, ol, li, dl, dt, dd, h1, h2, h3, h4, h5, h6, p, td, th, address, blockquote, pre, code, form, fieldset, legend, input, textarea { margin: 0; font-style: normal; line-height: normal; font-size: 12px; }
    h1, h2, h3, h4, h5, h6 {
        font-weight: normal;
    }

    .Tablepad {
        font-style: normal;
        padding: 10px;
    }

    .Text3 {
        border-bottom: 1px solid #ddd;
    }

    th, td {
        padding: 5px;
        text-align: left;
    }

    STLRImage {
        padding-left: 150px;
    }

    .Tenets {
        font-size: 14px;
        color: #666;
        font-weight: bold;
        padding: 4px;
    }

    .Text2 {
        font-size: 14px;
        font-style: normal;
        font-weight: bold;
        font-variant: normal;
        color: #000;
    }

    fieldset, img {
        border: none;
    }

    input, textarea, select {
        font-family: inherit;
        font-size: inherit;
        font-weight: inherit;
    }

    address, cite {
        font-style: normal;
    }

    table {
        border-collapse: collapse;
        vertical-align: top;
        font-size: 12px;
        line-height: normal;
        text-align: center;
    }

    caption, th {
        text-align: left;
    }

    a {
        text-decoration: none;
    }

    section, article, header, footer, nav, aside, hgroup {
        display: block;
    }

    body {
        font: 62.5%/2.4em "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
    }

    h1 {
        font-size: 2.4em;
    }

    h2 {
        font-size: 1.8em;
    }

    h3 {
        font-size: 1.8em;
        color: #FFF;
    }

    h4, h5, h6,
    dt, legend {
        font-size: 1.4em;
        line-height: 1.7143em;
        text-transform: uppercase;
        font-weight: bold;
    }

    .STLRH3 {
        font-size: 18px;
        vertical-align: text-top;
        font-weight: bold;
        padding: 3px;
    }
</style>
@Model.student.FirstName @Model.student.LastName
@DateTime.Now.ToShortDateString()
Graphic should show here:

I will attached zip file withASPOSEtest.zip (2.0 KB)
view file and ASPOSE code to make it easier for you to read.

// ASPOSE
Aspose.Pdf.License license = new Aspose.Pdf.License();
license.SetLicense(“Aspose.Pdf.lic”);
string html = ViewRenderer.RenderView("~/Views/Home/GeneratePDF-ASPOSE.cshtml", Session[“viewModel”]);

                // convert string to stream
                byte[] byteArray = Encoding.UTF8.GetBytes(html);
                //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
                MemoryStream stream = new MemoryStream(byteArray);

                // import an HTML document
                Aspose.Pdf.HtmlLoadOptions options = new Aspose.Pdf.HtmlLoadOptions();
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(stream, options);
                pdfDocument.Pages.Add();

                ArrayList watermark = new ArrayList();
                watermark.Add("UNOFFICIAL");
                watermark.Add("UNOFFICIAL");
                watermark.Add("UNOFFICIAL");

                // arrange multiline text stamp text
                FormattedText ft = new FormattedText(watermark[0].ToString(), System.Drawing.Color.LightGray, "Helvetica", EncodingType.Winansi, false, 80);
                for (int i = 1; i < watermark.Count; i++)
                    ft.AddNewLineText(watermark[i].ToString());

                TextStamp stamp = new TextStamp(ft);
                stamp.Background = true;
                stamp.Opacity = 0.5;
                stamp.RotateAngle = -45;
                stamp.TextAlignment = HorizontalAlignment.Left;
                stamp.HorizontalAlignment = HorizontalAlignment.Left;
                //stamp.VerticalAlignment = VerticalAlignment.Center;

                // add stamp to page collection
                pdfDocument.Pages[1].AddStamp(stamp);

                MemoryStream stream2 = new MemoryStream();
                pdfDocument.Save(stream2, Aspose.Pdf.SaveFormat.Pdf);
                return File(stream2.ToArray(), "application/pdf", "Outputfile.pdf");
// ASPOSE
                    Aspose.Pdf.License license = new Aspose.Pdf.License();
                    license.SetLicense("Aspose.Pdf.lic");
                    string html = ViewRenderer.RenderView("~/Views/Home/GeneratePDF-ASPOSE.cshtml", Session["viewModel"]);

                    // convert string to stream
                    byte[] byteArray = Encoding.UTF8.GetBytes(html);
                    //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
                    MemoryStream stream = new MemoryStream(byteArray);

                    // import an HTML document
                    Aspose.Pdf.HtmlLoadOptions options = new Aspose.Pdf.HtmlLoadOptions();
                    Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(stream, options);
                    pdfDocument.Pages.Add();

                    ArrayList watermark = new ArrayList();
                    watermark.Add("UNOFFICIAL");
                    watermark.Add("UNOFFICIAL");
                    watermark.Add("UNOFFICIAL");

                    // arrange multiline text stamp text
                    FormattedText ft = new FormattedText(watermark[0].ToString(), System.Drawing.Color.LightGray, "Helvetica", EncodingType.Winansi, false, 80);
                    for (int i = 1; i < watermark.Count; i++)
                        ft.AddNewLineText(watermark[i].ToString());

                    TextStamp stamp = new TextStamp(ft);
                    stamp.Background = true;
                    stamp.Opacity = 0.5;
                    stamp.RotateAngle = -45;
                    stamp.TextAlignment = HorizontalAlignment.Left;
                    stamp.HorizontalAlignment = HorizontalAlignment.Left;
                    //stamp.VerticalAlignment = VerticalAlignment.Center;

                    // add stamp to page collection
                    pdfDocument.Pages[1].AddStamp(stamp);

                    MemoryStream stream2 = new MemoryStream();
                    pdfDocument.Save(stream2, Aspose.Pdf.SaveFormat.Pdf);
                    return File(stream2.ToArray(), "application/pdf", "Outputfile.pdf");
@model myProject.Models.myViewModel

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <style media="screen" type="text/css">
        body,
        ul, ol, li, dl, dt, dd,
        h1, h2, h3, h4, h5, h6,
        p, td, th, address, blockquote,
        pre, code,
        form, fieldset, legend, input, textarea {
            margin: 0;
            font-style: normal;
            line-height: normal;
            font-size: 12px;
        }

        h1, h2, h3, h4, h5, h6 {
            font-weight: normal;
        }

        .Tablepad {
            font-style: normal;
            padding: 10px;
        }

        .Text3 {
            border-bottom: 1px solid #ddd;
        }

        th, td {
            padding: 5px;
            text-align: left;
        }

        STLRImage {
            padding-left: 150px;
        }

        .Tenets {
            font-size: 14px;
            color: #666;
            font-weight: bold;
            padding: 4px;
        }

        .Text2 {
            font-size: 14px;
            font-style: normal;
            font-weight: bold;
            font-variant: normal;
            color: #000;
        }

        fieldset, img {
            border: none;
        }

        input, textarea, select {
            font-family: inherit;
            font-size: inherit;
            font-weight: inherit;
        }

        address, cite {
            font-style: normal;
        }

        table {
            border-collapse: collapse;
            vertical-align: top;
            font-size: 12px;
            line-height: normal;
            text-align: center;
        }

        caption, th {
            text-align: left;
        }

        a {
            text-decoration: none;
        }

        section, article, header, footer, nav, aside, hgroup {
            display: block;
        }

        body {
            font: 62.5%/2.4em "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
        }

        h1 {
            font-size: 2.4em;
        }

        h2 {
            font-size: 1.8em;
        }

        h3 {
            font-size: 1.8em;
            color: #FFF;
        }

        h4, h5, h6,
        dt, legend {
            font-size: 1.4em;
            line-height: 1.7143em;
            text-transform: uppercase;
            font-weight: bold;
        }

        .STLRH3 {
            font-size: 18px;
            vertical-align: text-top;
            font-weight: bold;
            padding: 3px;
        }
    </style>
</head>
<body style="align-content:center">
    <div style="margin: 5px 25px 5px 25px; vertical-align:middle;">
        <div style="font-size:medium; height: 60px; width: 800px; border-bottom-width:4px; border-bottom-style:double;">
            <div style="float:left; font-size:medium; height: 55px; width: 300px;">
                @Model.student.FirstName&nbsp;@Model.student.LastName
                <br>
                @DateTime.Now.ToShortDateString()
            </div>
            <div style="float:left; text-align:center; font-size:medium; height: 55px; width: 200px;">
                Graphic should show here: <img src="~/Images/Badge.jpg" width="200" height="45" />
            </div>
        </div>
    </div>

</body>
</html>

@LoganJH,
We are working over your query and will get back to you soon.

@LoganJH,
We are sorry for the delay. Your code example is incomplete and missing view model code which you are sending to view through a session object. Kindly prepare a small MVC project application, which reproduces this problem in your environment, and then send us a Zip of this project. We will investigate and share our findings with you.

Fixed the images, used a absolute URL on web server, not relative path in MVC application code. This case/ticket can be closed. Thank you

@LoganJH,
It is nice to hear from you that the problem has been resolved. If you require any further information, please feel free to contact us.