I am currently facing one of the biggest challenges in learning programming with regards to downloading contents in a DIV tag in PDF.
I have asked this question before but I could not get a solution in that regard.
The thing is I have 3 web pages (uploadPDF.aspx, uploadword.aspx and wordpdf.aspx). After a user uploads a PDF file in uploadPDF and clicks on a button, the user will be redirected to wordpdf.aspx. Also, if user uploads word file in uploadword.aspx and clicks on a button, user will be redirected to wordpdf.aspx as well. Either way, the redirect leads to wordpdf.aspx.
Then on the wordpdf.aspx page, the document can be seen displayed in a DIV tag along with a QR code image. The document can be either word document or pdf document. The QR image is displayed on the word or PDF Document, and can be moved around to wherever position the user see fit.
But I don’t know how to download it in PDF. Can anyone help please?
This is the complete wordpdf.aspx page and wordpdf.aspx.cs. where the document is displayed.
HTML
<div class="contentt" style="width: 100%; margin: 0 auto;">
<asp:Panel Class="print-contents" ID="pnlContents" runat="server">
<div id="dvContainer" runat="server" style="border: 0.5px solid #e4e7e8;"></div>
<asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="80px" />
</asp:Panel>
</div>
<br />
<div style="margin: 0 auto;">
<asp:Button ID="Downloadbtn" CssClass="btn navbar-btn" Text="Download Document" runat="server" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="https://volodymyrbaydalka.github.io/docxjs/dist/docx-preview.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.18/mammoth.browser.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
<script src="~/js/bootstrap.min.js"></script>
<script src="~/docx-preview.min.js"></script>
<script src="~/js/docx-preview.js"></script>
<script type="text/javascript" src="~/Scripts/docx-preview.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "wordpdf.aspx/GetFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
if (r.d.ContentType != 'application/pdf') {
var doc = new File([new Uint8Array(r.d.Data)], r.d.ContentType);
if (doc != null) {
var docxOptions = Object.assign(docx.defaultOptions, {
useMathMLPolyfill: true
});
var container = document.querySelector("#dvContainer");
container.innerHTML = "";
docx.renderAsync(doc, container, null, docxOptions);
}
}
else {
LoadPdfFromBlob(r.d.Data);
}
}
});
});
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
var pdfDoc = null;
var scale = 1;
var resolution = 1;
function LoadPdfFromBlob(blob) {
pdfjsLib.getDocument({ data: blob }).promise.then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
var pdf_container = document.getElementById("dvContainer");
pdf_container.innerHTML = "";
pdf_container.style.display = "block";
for (var i = 1; i <= pdfDoc.numPages; i++) {
RenderPage(pdf_container, i);
}
});
};
function RenderPage(pdf_container, num) {
pdfDoc.getPage(num).then(function (page) {
var canvas = document.createElement('canvas');
canvas.id = 'pdf-' + num;
ctx = canvas.getContext('2d');
pdf_container.appendChild(canvas);
var spacer = document.createElement("div");
spacer.style.height = "20px";
pdf_container.appendChild(spacer);
var viewport = page.getViewport({ scale: scale });
canvas.height = resolution * viewport.height;
canvas.width = resolution * viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport,
transform: [resolution, 0, 0, resolution, 0, 0]
};
page.render(renderContext);
});
};
</script>
<script type="text/javascript">
//this JavaScript code is used to move the Image to anay position on the document
var dragItem = document.querySelector("#Image1");
var container = document.querySelector("#pnlContents");
var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
document.addEventListener("touchstart", dragStart, false);
document.addEventListener("touchend", dragEnd, false);
document.addEventListener("touchmove", drag, false);
document.addEventListener("mousedown", dragStart, false);
document.addEventListener("mouseup", dragEnd, false);
document.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.type === "touchstart") {
initialX = e.touches[0].clientX - xOffset;
initialY = e.touches[0].clientY - yOffset;
} else {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
}
if (e.target === dragItem) {
active = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (active) {
e.preventDefault();
if (e.type === "touchmove") {
currentX = e.touches[0].clientX - initialX;
currentY = e.touches[0].clientY - initialY;
} else {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
}
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, dragItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
</script>
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindCardAndQR();
}
}
[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 DocumentTable WHERE Id = @Id", con))
{
cmd.Parameters.AddWithValue("@Id", HttpContext.Current.Session["Document"]);
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 = bytes, ContentType = type };
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
private void BindCardAndQR()
{
if (Session["Document"] != null)
{
int id = Convert.ToInt32(Session["Document"]);
string sql = "SELECT * FROM DocumentTable WHERE Id = @Id";
SqlParameter[] parameters = new[] { new SqlParameter("@Id", id) };
DataTable dt = SelectFromDatabase(sql, parameters);
// Binding Image control for QR
byte[] QRBytes = GetQRCodeBytes(ToAbsoluteUrl("~/VPage.aspx?Id=" + Request.QueryString["Id"]));
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
}
else
{
Response.Redirect("Homepage.aspx");
}
}
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));
}
public byte[] GetQRCodeBytes(string url)
{
//QR code generated here
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);
}
}
}