I am trying to have a single page that will can be used to display either a word (.doc/.docx) or a PDF file. Instead of having two pages, each for word and pdf files. It’s a success but printing either of these formats in PDF is where I have issues.
After inserting a word or pdf file into my database table and redirect to another page, the word/pdf file is displayed on the redirected page. On the page, there is a div container that the word or pdf file will be displayed in. I want to learn how to print the file in PDF that displays there regardless of the format (whether it’s a .doc, .docx or .pdf file that displays in there).
Here is the HTML with the div container that displays word or pdf files
<div class="col-sm-10" style="width: 100%; padding: 10px; margin: 0 auto;">
<div class="col-sm-10" style="margin: 0 auto; padding: 6px;">
<div class="container-fluid" id="card" style="width: 100%; height: 100%; margin: 0 auto; border: 1px solid #e4e7e8;">
<div id="parent" style="margin: 0 auto; display: flex; position: center; width: 100%;">
<div class="contentt" runat="server" id="DivContent" style="margin: 0 auto;">
<div id="dvContainer" runat="server" style="margin: 0 auto;"></div>
<asp:Image ID="Image1" runat="server" ImageUrl="TesingImg.jpg" BorderStyle="None" Width="80px" Height="80px" />
</div>
</div>
</div>
</div>
<asp:Button ID="Downloadbtn" Text="Download" runat="server"/>
</div>
This is how the file is being selected from the database using Web method static object, GetFile().
[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["DocumentID"]);
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);
}
}
Plugins
<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>
Javascript function that displays the file (.doc, .docx or .pdf) on the page.
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "2.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>
I tried to enclose the div container in a printpanel and use this pdf print method to print but it did not work. Please how can I do this?
<asp:Panel ID="Panel1" runat="server">
<div class="contentt" runat="server" id="DivContent" style="margin: 0 auto;">
<div id="dvContainer" runat="server" style="margin: 0 auto;"></div>
<asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="80px" />
</div>
</asp:Panel>
<asp:Button ID="Downloadbtn" Text="Download" runat="server" OnClick="Downloadbtn_Click"/>
There is an image control also in the div tag. the image control can be moved to change position dynamically to anywhere in the div an be printed along with the word/pdf file.
Here is the javascript that aids in moving the image control to a desired location in the div tag
<script type="text/javascript">
var dragItem = document.querySelector("#Image1");
var container = document.querySelector("#subpage");
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>
PDF Printing
protected void Downloadbtn_Click(object sender, EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AddHeader("Content-Disposition", "Attachment; filename=Document.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter StringWriter = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(StringWriter);
DivContent.RenderControl(hw);
Document doc = new Document(PageSize.A4,50f,50f,100f,30f);
HTMLWorker htw = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
StringReader sr = new StringReader(StringWriter.ToString());
htw.Parse(sr);
doc.Close();Response.Write(doc);
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}