Spire.XLS is a professional Excel API that enables developers to create, manage, manipulate, convert and print Excel worksheets. Get free and professional technical support for Spire.XLS for .NET, Java, Android, C++, Python.

Wed Feb 22, 2017 9:20 pm

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();

}
}
}
Attachments
pdfData.zip
(22.95 KiB) Downloaded 293 times

lsong
 
Posts: 36
Joined: Wed Feb 01, 2017 4:13 pm

Thu Feb 23, 2017 7:23 am

Dear Lucy,

Many thanks for the detailed information.
I have noticed the issue and posted it to our Dev team. Once it is fixed and the Spire.Office hotfix is available, we will notify you.
Sorry for inconvnience caused.

Sincerely,
Betsy
E-iceblue support team
User avatar

Betsy.jiang
 
Posts: 3099
Joined: Tue Sep 06, 2016 8:30 am

Thu Feb 23, 2017 6:06 pm

Since we are using Spire.Office, when you need to compile a new Hot fix for the Spire.Office, could you please make sure it’s published on NuGet package? Thanks.

lsong
 
Posts: 36
Joined: Wed Feb 01, 2017 4:13 pm

Fri Feb 24, 2017 1:35 am

Dear Lucy,

Thanks for the information.
We will inform you when the Spire.Office hotfix for your issue is available on NuGet :) .

Sincerely,
Betsy
E-iceblue support team
User avatar

Betsy.jiang
 
Posts: 3099
Joined: Tue Sep 06, 2016 8:30 am

Tue Feb 28, 2017 12:28 am

Hi,
Could you please give me a rough estimate of when you are going to resolve this issue?

Thanks,
Lucy

lsong
 
Posts: 36
Joined: Wed Feb 01, 2017 4:13 pm

Tue Feb 28, 2017 6:41 am

Dear Lucy

Thanks for your inquiry.
After further investigation, we found you use the same stream many times, and the reason caused the issue is that you didn't dispose the steam after using. Please do that, and here is sample code for your reference. I also attach whole code for checking.
Code: Select all
            _ms.Dispose();
            _ms = new MemoryStream();
            loPDF.SaveToStream(_ms, Spire.Pdf.FileFormat.PDF);

If there is any question, please let me know.

Sincerely,
Betsy
E-iceblue support team
Attachments
WebForm1.aspx.cs.zip
(2.22 KiB) Downloaded 317 times
User avatar

Betsy.jiang
 
Posts: 3099
Joined: Tue Sep 06, 2016 8:30 am

Thu Mar 02, 2017 7:45 am

Dear Lucy,

Did you test the solution ?
Has your issue been solved ?

Thanks,
Betsy
E-iceblue support team
User avatar

Betsy.jiang
 
Posts: 3099
Joined: Tue Sep 06, 2016 8:30 am

Thu Mar 02, 2017 9:16 pm

Hi Betsy,
We just tested your solution and it worked fine.

Thanks!
Lucy

lsong
 
Posts: 36
Joined: Wed Feb 01, 2017 4:13 pm

Fri Mar 03, 2017 1:25 am

Dear Lucy,

Thanks for your feedback.
Please feel free to contact us if there is any question :) .

Sincerely,
Betsy
E-iceblue support team
User avatar

Betsy.jiang
 
Posts: 3099
Joined: Tue Sep 06, 2016 8:30 am

Return to Spire.XLS