How to display a PDF stream in a browser using javascript
Asked Answered
M

3

24

I am accessing an existing WCF web service (which returns a PDF as a byte stream) using jquery's ajax methods.

When the call to the service completes, I end up with a javascript variable containing a PDF (the variable has the binary data in, starting "%PDF-1.4...").

I'd like to display this PDF in a new browser window, but I'm having difficulty achieving this.

My research so far shows that I might be able to achieve what I want using a data: uri, so my code that's called when the ajax call completes is as follows:

function GotPDF(data)
{
    // Here, data contains "%PDF-1.4 ..." etc.
    var datauri = 'data:application/pdf;base64,' + Base64.encode(data);
    var win = window.open("", "Your PDF", "width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no");
    win.document.location.href = datauri;
}

This causes a new browser window to open, but the contents are blank.

Interestingly, if I point my browser (IE9) at an existing file on my local disk by using a file: uri, such as file://c:/tmp/example.pdf, then I get the same result, i.e. a blank window.

Is there any way I can display this PDF data?

Menken answered 23/3, 2012 at 13:42 Comment(0)
U
19

Code you wrote does not display anything, simply open a blank window (location.href is an hash for browsing history, not the content of the page).

To display a PDF you have, at least, following options:

× Embed the PDF viewer inside an object tag. It may not be as straightforward as you may imagine, take a look to this post for sample code. In short it should be something like this:

<object data="your_url_to_pdf" type="application/pdf">
    <div>No PDF viewer available</div>
</object>

That's basic code but I suggest to follow what I say in the linked post if you need higher cross-browser compatibility (it also contains a few examples about how you might try to detect support for a PDF viewer).

× Download the file to local computer (simply add the full URL of your web service method that produces the file, do not forget to add the proper Content-Disposition in the header).

× Open the file into a new browser window. Create a normal a tag as you point to a PDF file on-line that you want to display in a new window. Change the href to javascript:functionName and in that function produce the URI you'll use to call the web service method.

Whatever you'll do, do not forget to set the proper MIME type in your response moreover you method shouldn't return a byte stream (even if encoded) but a valid response for your web browser.

Unveiling answered 23/3, 2012 at 13:54 Comment(0)
F
8

If you are using <embed> or <object> tag to display a streamed PDF file (or other file types) from a server as in:

<object data="SomeServlet?do=get_doc&id=6" type="application/pdf" width="800" height="400">

make sure the server sends the proper http content-disposition value, which in this case would be inline.

Faultfinder answered 15/2, 2014 at 21:39 Comment(0)
K
0

document.getElementById('uploadForm').addEventListener('submit', function(event) {
    event.preventDefault();

    // ทำการโหลดไฟล์ PDF และบันทึก
    var pdfFileURL = '/web/viewer.html?file=%2Fassets%2Fpdf%2Fuploaded-file.pdf'; // เปลี่ยนเส้นทางไฟล์ตามที่คุณเก็บไฟล์

    var xhr = new XMLHttpRequest();
    xhr.open('GET', pdfFileURL, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function() {
        var arrayBuffer = xhr.response;
        if (arrayBuffer) {
            // เรียกใช้ PDF.js library เพื่อดึงข้อมูลจากไฟล์ PDF
            pdfjsLib.getDocument(arrayBuffer).then(function(pdf) {
                // ดึงหน้าแรกของไฟล์ PDF
                pdf.getPage(1).then(function(page) {
                    // สร้าง canvas เพื่อแสดงรูปภาพจากตราปั๊ม
                    var canvas = document.createElement('canvas');
                    var context = canvas.getContext('2d');
                    var viewport = page.getViewport({ scale: 1.0 });

                    // ตั้งค่าขนาดของ canvas ตาม viewport
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;

                    // ดึงข้อมูลจาก PDF และวาดลงบน canvas
                    var renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };

                    page.render(renderContext).then(function() {
                        // นำ canvas ไปแปลงเป็น data URL
                        var dataURL = canvas.toDataURL();

                        // แสดงตราปั๊มในฟอร์ม
                        var pumpImageContainer = document.getElementById('pumpImageContainer');
                        var pumpImage = document.getElementById('pumpImage');

                        // สร้างเส้นคั่นตราปั๊ม
                        context.beginPath();
                        context.moveTo(0, canvas.height / 2);
                        context.lineTo(canvas.width, canvas.height / 2);
                        context.strokeStyle = 'blue'; // สีน้ำเงิน
                        context.lineWidth = 5;
                        context.stroke();

                        // แสดงข้อความตามที่ระบุ
                        context.fillStyle = 'blue'; // สีน้ำเงิน
                        context.font = '20px Arial';

                        var textLines = ['CHT', 'ชื่อ', 'วันที่ ' + new Date().toLocaleDateString()];
                        var lineHeight = 30;
                        var startY = canvas.height / 2 - (lineHeight * textLines.length) / 2;

                        textLines.forEach(function(line, index) {
                            context.fillText(line, canvas.width / 2 - context.measureText(line).width / 2, startY + index * lineHeight);
                        });

                        // แสดงรูปตราปั๊มในฟอร์ม
                        pumpImage.src = dataURL;
                        pumpImage.alt = 'รูปตราปั๊ม';
                        pumpImageContainer.style.display = 'block';
                    });
                });
            });
        }
    };

    xhr.send();
});
<form id="uploadForm" action="/YourController/Upload" method="post" enctype="multipart/form-data">
    <label for="pdfFile">เลือกไฟล์ PDF:</label>
    <input type="file" name="pdfFile" id="pdfFile" required />
    
    <label for="name">ชื่อ:</label>
    <input type="text" name="name" id="name" required />
    
    <input type="submit" value="อัปโหลด" />
</form>

<div id="pumpImageContainer">
    <img id="pumpImage" alt="รูปตราปั๊ม" />
</div>
Kamasutra answered 21/1 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.