Hi,
I am working on creating a pdf file from a template and xml data file. I need to apply a water mark image to the background of the PDF file. However the water mark doesn't show in the PDF file. Below is my code, I also attached the files required to run the code.
Could you please let me know what's wrong?
Please also make sure that we want to be able to view the water mark image in all types of browsers(IE, google chrome, firefox, etc).
Thanks,
Lucy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Spire.Xls;
using Spire.Pdf;
using System.Drawing;
namespace PDFTest
{
public partial class _Default : Page
{
private MemoryStream _ms = null;
protected void Page_Load(object sender, EventArgs e)
{
try
{
CreateReportWorkBook();
string outputFileName = string.Format("{0}{1}", "TestResult", ".pdf");
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + outputFileName);
Response.AppendHeader("Content-Length", _ms.ToArray().Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(_ms.ToArray());
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Flush();
Response.End();
}
catch (Exception ex)
{
}
finally
{
if (_ms != null)
_ms.Dispose();
}
}
public void CreateReportWorkBook()
{
bool _isDocumentTypePDF = false;
string _templatePath = string.Empty;
string _outputFileName = string.Empty;
string _sheetName = string.Empty;
int tempInt = 0;
float _tempFloat = 0;
double _tempDouble = 0.0;
var xml = XDocument.Load("pdfData.xml");
if (xml != null)
{
var rowArray = xml.Descendants("r").ToArray();
var _rows = rowArray.Count();
var _fileStream = new FileStream("PlanSponsorPlanAssetSummaryTemplate.XLSX", FileMode.Open, FileAccess.Read);
var _myWorkBook = new Workbook();
_myWorkBook.LoadFromStream(_fileStream);
var _myWorkSheet = _myWorkBook.Worksheets[0];
_myWorkSheet.Name = "MySheet";
//read data row by row from xml file and insert into new excel file
for (int i = 0; i < _rows; i++)
{
//As the first row (index:0) in the excel template contains the report Heading. Hence, adding 1 to the index number and starting from next row.
int rowNumber = _isDocumentTypePDF ? i + 3 : i + 1;
int rowCount = _isDocumentTypePDF ? _myWorkSheet.Range.RowCount + 2 : _myWorkSheet.Range.RowCount;
//Gets the row count from the template : If the count is less than or equal to the total row number of the xml, then it inserts a new row into excel file.
if (rowCount <= rowNumber)
{
_myWorkSheet.InsertRow(rowNumber + 1, 1, InsertOptionsType.FormatAsAfter);
}
//Gets total number of columns from xml file.
int columnsCount = rowArray[i].Nodes().Count();
if (_myWorkSheet.Columns.Count() < columnsCount)
{
columnsCount = _myWorkSheet.Columns.Count();
}
CellRange[] Cells = _myWorkSheet.Rows[rowNumber].Cells;
for (int j = 0; j < columnsCount; j++)
{
var value = rowArray[i].Element("c" + (j + 1)).Value;
//Checks if the Data Format received from the template file is of type "Number", thats holds only numeric data, and applies equivalent NPOI Data Format for the particular cell.
if (Cells[j].NumberFormat.Contains("0") && Regex.Matches(value, @"[a-zA-Z]").Count == 0 && (int.TryParse(value, out tempInt) || double.TryParse(value, out _tempDouble) || float.TryParse(value, out _tempFloat)))
{
var value1 = tempInt > 0 ? tempInt : _tempFloat > 0 ? _tempFloat : _tempDouble > 0 ? _tempDouble : 0;
Cells[j].NumberValue = value1;
}
//Checks if the Data Format for the cell is of type 'Date', and applies equivalent NPOI Data Format for the particular cell.
else if (Cells[j].NumberFormat.Contains("d") && Regex.Matches(value, @"[a-zA-Z]").Count == 0 && !string.IsNullOrEmpty(value))
{
DateTime oDate = Convert.ToDateTime(value);
Cells[j].DateTimeValue = oDate;
}
else
{
if (!string.IsNullOrEmpty(value))
{
Cells[j].Text = value;
}
}
}
}
_ms = new MemoryStream();
_myWorkBook.SaveToStream(_ms, Spire.Xls.FileFormat.Version2007);
GeneratePDFReportDocument();
}
}
private void GeneratePDFReportDocument()
{
Workbook loWorkBook = new Workbook();
loWorkBook.LoadFromStream(_ms, true);
System.Drawing.Image loLogoImage = System.Drawing.Image.FromFile(Server.MapPath("ReportsWPLogo.png"));
Worksheet loSheet = loWorkBook.Worksheets[0];
loSheet.PageSetup.LeftHeaderImage = loLogoImage;
loSheet.PageSetup.LeftHeader = "&G";
float foatWatermarkPositionX = 100, foatWatermarkPositionY = 250;
if (loSheet.PageSetup.Orientation == PageOrientationType.Landscape)
{
foatWatermarkPositionX = 200;
foatWatermarkPositionY = 100;
}
loWorkBook.SaveToStream(_ms, Spire.Xls.FileFormat.PDF);
MemoryStream loPDFStream = new MemoryStream();
loWorkBook.SaveToStream(loPDFStream, Spire.Xls.FileFormat.PDF);
PdfDocument loPDF = new PdfDocument();
loPDF.UseHighQualityImage = true;
loPDF.LoadFromStream(loPDFStream);
System.Drawing.Image loImage = System.Drawing.Image.FromFile(Server.MapPath("ReportsWPWatermark.png"));
foreach (PdfPageBase loPage in loPDF.Pages)
{
loPage.BackgroundImage = loImage;
loPage.BackgroundRegion = new RectangleF(foatWatermarkPositionX, foatWatermarkPositionY, loImage.Size.Width, loImage.Size.Height);
}
loPDF.ViewerPreferences.FitWindow = true;
loPDF.ViewerPreferences.PageMode = PdfPageMode.UseOutlines;
_ms.Flush();
loPDF.SaveToStream(_ms, Spire.Pdf.FileFormat.PDF);
loPDFStream.Dispose();
loPDF.Close();
}
}
}