- Embed PDF in HTML
- Method 1: Using Object Tag
- Method 2: Using iframe
- Method 3: Using embed tag
- Method 4: Using PDF.js
- Встраивание документа PDF в веб-страницу
- Способы внедрения документа в формате PDF в HTML страницу
- PDF.js
- Adobe Document Cloud
- Тестирование, сравнение и выводы
- Проверка
- Заключение
- How to Embed PDF in HTML
- Ways of putting a PDF document in HTML
- Example of embedding a PDF file in an HTML document:
- Result
- How to embed PDF viewer in HTML
- Example of adding a PDF file to the HTML by using the ‘object’ tag:
- Can we prevent the pdf from downloading?
Embed PDF in HTML
For those who want a professional and beautifully designed way to display documents onto their webpages, being able to embed pdf html code onto their website would give them the ability to display interactive documents for users to use. Many companies and individiuals can benefit from being able to embed a pdf inside the html code for their websites, instead of traditional document display. Embedding pdf in the html code allows a more convenient way to display pdf documents which may not have been compatible with browsers before.
It is surely a put-off if you redirect your viewers to a third party application in order to display your pdf documents (such as drive links) and the user is now away from your webpage. The proability of his return is surely reduced if this method is used.
So let’s learn how to efficiently embed pdf documents into your webpage and display them and there.
For the tutorial, I’ll use an online document, which is my resume.
In case you wish to use a local file, replace the link with the name of the file, with the appropriate path, of course.
Method 1: Using Object Tag
The first method to embed pdf in html is by making use of the object tag in html. The object defines the object that is to be embedded in the page, which in this case is the pdf file to be displayed on the web page, of course.The object tag isn’t just used to embed a pdf html code into a webpage; it can also be used to embed ActiveX, Flash, video, audio, and Java applets. The object embed a pdf html tag can be used to attach interactive documents.
Lets see how the code looks for the same:
- As visible above, the data attribute of the object tag is used to specify the name/address of the file that is to be displayed.
- Lets create an HTML file named index.html to test this out:
- Now open the index.html file in your browser and the pdf file should be visible in it.
- We observe that the size of the pdf file which we embedded is not appropriate, thefore we have style it accordingly.
- In this example, I will demonstrate how to display the pdf file in all the space available, by using -webkit-fill-available as the height and width of the object.
- The code for the object will be as follows for that:
- Also, it is always better to specify the file format of the data while using the object tag to eliminate possibilty of inaccurate browser compatibility.
Method 2: Using iframe
The second method to embed a pdf in an HTML web page is the iframe tag.
The iframe tag is widely used by web developers to embed files of various formats and even other webpages inside the concerned web page. Most browsers are compatible with this embed a pdf html code tag which is why this tag is widely used. This tag used to embed a pdf html code can also be used if a browser does not support PDF documents or the object tag.
- The method to use the iframe tag to display pdf in web pages should be clear from this code snippet:
- As visible in the above snippet, the method to use the iframe and object tags is quite similar.
- The data tag is replaced by src tag, the abbreviation of source which, although self-explanatory, specifies the source of the file to be embedded.
- The HTML file should have the following contents:
- Open the file in your browser and it should look like this:
- If you notice carefully, while using this method, a line with a shadow appears on the border of the embedded file. The file is rendered in a container, more accurately a frame.
Method 3: Using embed tag
The embed tag isn’t used as often as the previous tags to embed a pdf html code into a website because when it is used to embed a pdf html code into a website if the browser does not support PDF files, the person using the website will see a blank. embed is used to embed a pdf html code when there is no need for a mechanism to be supplied for fallback content in the embed a pdf html code.
Similar to the previous methods, the syntax can be understood by this example:
Should look like this:
Method 4: Using PDF.js
External libraries can also be used to embed pdf files into html web pages. These are generally used for custom features.
Let us try it out with PDF.js .
PDF.js is a JavaScript library written by Mozilla. Since it implements PDF rendering in vanilla JavaScript, it has cross-browser compatibility and does not require additional plugins to be installed.
With PDF.js, PDFs are downloaded via AJAX and rendered onto a canvas element using native drawing commands. To improve performance, a lot of the processing work happens in a web worker.
To get started, all you need to do is to download a recent copy of PDF.js and you’re good to go.
(For this tutorial, go for the stable version)
Once you have downloaded the file, extract it. You will see two folders, namely
web and build.
The HTML file needs to point to the pdf.js source code and to our custom application code (simple.js). We also create a ‘canvas’ element, which we want the first page of the PDF to be rendered into:
Now all that’s missing is our simple.js code that leverages the PDF.js API to render the first page.
Here, I am assuming that you need to embed a pdf file which is named test.pdf
var loadingTask = PDFJS.getDocument("/test.pdf"); loadingTask.promise.then( function(pdf) < // Load information from the first page. pdf.getPage(1).then(function(page) < var scale = 1; var viewport = page.getViewport(scale); // Apply page dimensions to the element. var canvas = document.getElementById("pdf"); var context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; // Render the page into the element. var renderContext = < canvasContext: context, viewport: viewport >; page.render(renderContext).then(function() < console.log("Page rendered!"); >); >); >, function(reason) < console.error(reason); >);
We can now work on the integration. To do this, we create a simple HTML file that will include the viewer via an iframe. This allows us to embed the viewer into an existing webpage very easily. The viewer is configured via URL parameters, a list of which can be found here. For our example, we will only configure the source PDF file. For more advanced features (like saving the PDF document to your web server again), you can simply start modifying the viewer.html file provided by PDF.js:
These are the four methods that I use for embedding a pdf into my html webpages.
Hope you learnt something of value from this article!
Встраивание документа PDF в веб-страницу
Эта статья рассказывает о том, как сделать отображение документа формата PDF непосредственно на странице сайта.
Важно, чтобы решение было совместимо со всеми платформами – браузерами и операционными системами, в том числе мобильными. Иначе большая часть пользователей не сможет увидеть документ.
Ещё желательно, чтобы была возможность указания определённого места документа – это удобно для больших документов каталогов, чтобы каталог открывался пользователю сразу на нужной странице.
Способы внедрения документа в формате PDF в HTML страницу
Тег
Тег
Простой в использовании, более новый, по сравнению с EMBED, HTML5:
В отличие от EMBED, можно задать текст для отображения в случае, если показать документ не получилось. Это может быть альтернативный текст или прямая ссылка на скачивание документа.
PDF.js
A general-purpose, web standards-based platform for parsing and rendering PDFs.
Требуется установка файлов проекта PDF.js на сайт. Установка несложная – просто скопировать файлы, но нужен доступ. Также при загрузке страницы будет загружаться просмотровщик – это увеличит время загрузки страницы, потребуется настроить кеширование файлов на стороне клиента.
Adobe Document Cloud
Это тоже вариант, если использовать веб-версию Adobe Document Cloud, которая позволяет просматривать документы на веб-странице, а не в локальном приложении.
Тестирование, сравнение и выводы
Для просмотра и сравнения сделал https://nhutils.ru/blog/proverka-vstraivaniya-pdf-dokumenta-v-veb-stranitsu/, которую надо открыть на разных устройствах и в разных браузерах.
На мобильном можно открыть по коду:
Проверка
На десктопе работают все варианты.
Теги EMBED и OBJECT не работают на мобильных – на Android окно белое, на iPhone — показывается только первая страница документа, как картинка– нельзя листать страницы, менять масштаб тоже нельзя.
Внедрение документа PDF из Adobe Document Cloud тоже не работает – белое поле.
Только PDF.js показал документ на всех платформах, с возможностью листания и увеличения: Windows, Android, iOS.
Заключение
Универсальное решение для настольной и мобильных платформ – это PDF.js.
How to Embed PDF in HTML
There are several ways to include a PDF file in your HTML document:
Ways of putting a PDF document in HTML
Example of embedding a PDF file in an HTML document:
html> html> head> title>Title of the document title> head> body> h1>PDF Example h1> p>Open a PDF file a href="/uploads/media/default/0001/01/540cb75550adf33f281f29132dddd14fded85bfc.pdf">example a>. p> body> html>
Result
How to embed PDF viewer in HTML
You could try embedding the PDF file in an ‘object’ tag. Here is an example of how to do this:
Example of adding a PDF file to the HTML by using the ‘object’ tag:
html> html> head> title>PDF Example by Object Tag title> head> body> h1>PDF Example by Object Tag h1> object data="/uploads/media/default/0001/01/540cb75550adf33f281f29132dddd14fded85bfc.pdf" type="application/pdf" width="100%" height="500px"> p>Unable to display PDF file. a href="/uploads/media/default/0001/01/540cb75550adf33f281f29132dddd14fded85bfc.pdf">Download a> instead. p> object> body> html>
This code will display the PDF file in an object element in the HTML page. If the browser is unable to display the PDF file, it will show a fallback message with a download link.
Can we prevent the pdf from downloading?
Unfortunately, it is not possible to completely prevent a user from downloading a PDF file that is embedded in an HTML page. Even if you disable the right-click context menu, a user can still access the PDF file through the browser’s developer tools or by inspecting the page source.
However, you can make it more difficult for a user to download the PDF file by using various methods, such as:
- Converting the PDF file to an image format (such as JPEG or PNG) using a tool like ImageMagick or Ghostscript, and displaying the images in an HTML page. This way, the user will not be able to download the original PDF file directly, but they can still download the images.
- Using a JavaScript PDF viewer library like PDF.js, which can display PDF files in an HTML page using the browser’s built-in PDF rendering capabilities. You can customize the viewer to disable downloading and printing, but as I mentioned earlier, it is still possible for a user to access the PDF file through the browser’s developer tools or by inspecting the page source.
- An alternative strategy to consider is the use of CloudPDF, a unique cloud-based service designed specifically to protect PDF files from unauthorized downloads. Similar to PDF.js, CloudPDF provides a platform for viewing PDF files within the browser, but sets itself apart by disabling the download functionality for viewers, adding an extra layer of document control. CloudPDF achieves this through server-side rendering, a technique that prevents the PDF from being directly transferred or displayed in the client’s browser, making it more difficult for the document to be accessed via developer tools or page source inspection, thereby enhancing security significantly. While it’s important to note that no method is foolproof, the features provided by CloudPDF notably elevate the difficulty level for unauthorized access, making it a worthy consideration for those seeking enhanced document security.