In trying to print word file in PDF format I get this error below.
I have a container that shows word document data from database and a button that prints the word document inside the container but when I click on the button the word document does not print. Please I need help in making word document print.
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
BindWordAndQR();
}
}
//This is where I bind the QR code to the Image1 control, which is on the web form
private void BindWordAndQR()
{
if (Session["docx"] != null)
{
int id = Convert.ToInt32(Session["docx"]);
string sql = "SELECT * FROM WordTable WHERE Id = @Id";
SqlParameter[] parameters = new[] { new SqlParameter("@Id", id) };
// Bind Image3 for Card Image
DataTable dt = SelectFromDatabase(sql, parameters);
byte[] QRBytes = GetQRCodeBytes(ToAbsoluteUrl("~/wordfile.aspx") + "?Id=" + Request.QueryString["Id"]);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
}
}
public string ToAbsoluteUrl(string relativeUrl)
{
if (string.IsNullOrEmpty(relativeUrl))
{
return relativeUrl;
}
if (relativeUrl.StartsWith("/"))
{
relativeUrl = relativeUrl.Insert(0, "~");
}
if (!relativeUrl.StartsWith("~/"))
{
relativeUrl = relativeUrl.Insert(0, "~/");
}
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
//QR code is generated here
public byte[] GetQRCodeBytes(string url)
{
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap bi = encoder.Encode(url);
MemoryStream tmpSteam = new MemoryStream();
bi.Save(tmpSteam, ImageFormat.Jpeg);
return tmpSteam.ToArray();
}
public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
}
//This is where I display the word document file on the web form, using static object [webmethod]
[WebMethod(EnableSession = true)]
public static object GetFile()
{
try
{
string fileName = string.Empty;
byte[] bytes = null;
string type = string.Empty;
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tablereceipt WHERE Id = @Id", con))
{
cmd.Parameters.AddWithValue("@Id", HttpContext.Current.Session["Receiptdocx"]);
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
fileName = dr["Name"].ToString();
bytes = (byte[])dr["Data"];
type = dr["ContentType"].ToString();
}
}
con.Close();
}
}
return new { Name = fileName, Data = Convert.ToBase64String(bytes), ContentType = type };
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
//This is the print Section
protected void BtnPrinnt_Click(object sender, EventArgs e)
{
if (Session["docx"] != null)
{
int id = Convert.ToInt32(Session["docx"]);
string sql = "SELECT * FROM WordTable WHERE Id = @Id";
SqlParameter[] parameters = new[] {
new SqlParameter("@Id", id)
};
// Bind Image3 for Card Image
DataTable dt = SelectFromDatabase(sql, parameters);
if (dt.Rows.Count > 0)
{
byte[] QRBytes = GetQRCodeBytes(ToAbsoluteUrl("~/wordfile.aspx") + "?Id=" + Request.QueryString["Id"]);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(QRBytes);
byte[] pdfbytes = (byte[])dt.Rows[0]["Data"];
using (MemoryStream memoryStream = new MemoryStream())
{
var reader = new PdfReader(pdfbytes);
var stamper = new PdfStamper(reader, memoryStream);
var pdfContentByte = stamper.GetOverContent(1);
image.ScaleAbsolute(75f, 75f);
image.SetAbsolutePosition(reader.GetPageSize(1).Width / 2 - 100, 50);
pdfContentByte.AddImage(image);
stamper.Close();
byte[] bytess = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=Receipt.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytess);
Response.End();
}
}
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}