1
How to Save file via Document Viewer Manually.
Question asked by Hemant Yogi - 12/12/2024 at 6:26 AM
Answered
I am trying to save a file from the Document Viewer after applying a watermark. 

My objective is to load the document into the Document Viewer, apply a watermark, and then save the file to a specified path.

I attempted to achieve this by loading the document, obtaining a stream, and copying the stream to create a new file, but unfortunately, this approach did not work. 

I have also reviewed the documentation but couldn't find any methods or guidelines for performing this operation.

Here is a sample of the code I have tried:



var documentViewer = new DocumentViewer
{
    Width = 960,
    Height = 720,
    Resizable = true,
    Document = FilePath,
    DocumentOptions = new DocumentOptions
    {
        Format = DocumentFormat.Pdf,
        Watermarks = {
                        new TextWatermark
                        {
                            Text = "Contoso",
                            Rotation = -45,
                            Opacity = 50,
                            FontColor = Color.Red,
                            Width = 50,
                            Height = 50,
                            SizeIsPercentage = true
                        }
        }
    }
};
documentViewer.Hidden = true;

using (var fileStream = File.Create("D:\\PDF_POC\\Updated\\file.pdf"))
{
    using (var stream = documentViewer.Document.OpenWrite())
    {
        //stream.Seek(0, SeekOrigin.Begin);
        //stream.CopyTo(fileStream);

        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fileStream.Write(buffer, 0, len);
        }
    }
        
}


Let me know if you'd like further adjustments!

1 Reply

Reply to Thread
0
Cem Alacayir Replied
Employee Post Marked As Answer
Hi,
You can use DocumentConverter class to first convert your original document to a PDF with the watermarks, then you can pass this PDF to the DocumentViewer, see the below sample code:

var WatermarkedFilePath = @"D:\PDF_POC\Updated\file.pdf";

var pdfOutputOptions = new PdfOutputOptions
{
	Watermarks = new[] {
		new TextWatermark
		{
			Text = "Contoso",
			Rotation = -45,
			Opacity = 50,
			FontColor = Color.Red,
			Width = 50,
			Height = 50,
			SizeIsPercentage = true
		}
	}
};

//First convert your original file to a watermarked PDF file
DocumentConverter.Convert(FilePath, WatermarkedFilePath, pdfOutputOptions);

//Then load this watermarked PDF file in Document Viewer
var documentViewer = new DocumentViewer
{
	Width = 960,
	Height = 720,
	Resizable = true,
	Hidden = true,
	Document = WatermarkedFilePath
};

Reply to Thread