PDF in HTML

Как сделать ссылку на PDF в HTML

Сделать ссылку на PDF файл в HTML-странице весьма просто. Но есть некоторые расширенные возможности, которые возможно будут полезны тем, кто захочет ссылаться со своей web-страницы на различные части PDF-документов.

Для того, чтобы сделать ссылку на PDF файл в HTML, вам достаточно будет добавить в web-страницу следующий код: Our Products

После нажатия на эту ссылку, в браузере (или, если у вас настроено по-другому, в PDF-вьювере) откроется PDF-документ.

Но это слишком простой способ добавления ссылки на PDF в HTML.

К примеру, мы делаем ссылку на PDF-документ, состоящий из 1500 страниц.. И хотим, чтобы при нажатии клиентом на ссылку, документ открывался на 835-ой странице (ну не будет же он листать документ!).

Это реализуется очень просто:

Достаточно добавить в ссылку некоторые изменения, а именно: Our Products — Page 835 и при нажатии на созданную ссылку, документ откроется со страницы 835.

Но может быть необходимо сделать так, чтобы PDF-документ открывался на определенном разделе.

В этом случае поможет такое решение: Our Products — Best-Price

Обратите внимание, что этот способ чувствителен к регистру.

Как видим, есть несколько полезных и удобных вариантов при ссылках на PDF-документы в HTML.

Остались вопросы?

Если у Вас что-то не получилось или остались вопросы по данной проблеме — обратитесь к автору и он Вам поможет.

Станьте одним из экспертов!

Мы будем рады видеть в своих рядах людей, которые могут поделиться своим опытом с другими!

Linux (Ubuntu,Debian,Fedora), MS Windows (Server/Desktop), PHP.
Решение IT-проблем любой сложности.

Источник

Создание URL для открытия файла PDF на определенной странице

Страницы HTML могут содержать ссылки, которые открывают файлы PDF в веб-браузере с помощью модуля продукта Adobe Acrobat (Adobe Acrobat Professional или Standard, Adobe Acrobat 3D или Adobe Reader), установленного в поддерживаемые версии Netscape Navigator, Mozilla Firefox, Microsoft Internet Explorer или Safari (Mac OS).

При открытии файла PDF в браузере по умолчанию будет отображаться первая страница файла PDF. Вы можете добавить строку в ссылке HTML таким образом, что откроется файл PDF и в нем выполняется переход к указанной странице или указанной позиции. Для использования любого из этих методов выполните следующие действия:

Откройте файл PDF на конкретной странице

Для направления ссылки HTML на конкретную страницу файла PDF добавьте #page=[номер-страницы] в конец ссылки URL.

Например, этот тег HTML открывает страницу 4 файла PDF myfile.pdf:

Примечание. Если вы используете в ссылке адрес сервера UNC (\\servername\folder), настройте ссылку для открытия в место назначения, используя процедуру в следующем разделе. При использовании URL, содержащих адреса локального жесткого диска (c:\folder\), вы не сможете создать ссылку к номерам страниц или местам назначения. В продуктах Adobe Acrobat 7.0 ссылка на номера страниц работает только при использовании местоположений HTTP или HTTPS. Адреса UNC сервера будут работать только при использовании метода указания адресов так, как показано в следующем разделе этого документа.

Читайте также:  Php default class method

Откройте файл PDF в месте назначения

Место назначения является конечным пунктом ссылки и представлено текстом на панели «Места назначения». Места назначения позволяют задать пути навигации по набору документов Adobe PDF. Создание ссылки на место назначения рекомендуется при организации связей между документами, так как, в отличие от ссылки на страницу, ссылка на место назначения не изменяется при добавлении или удалении страниц в целевом документе.

Чтобы указать место назначения в Acrobat 7.0 (Professional или Standard):

1. Установите масштаб и размещение на странице таким образом, как вы хотите видеть на экране.

2. Выберите «Просмотр > «Вкладки навигации» > «Места назначения», чтобы открыть вкладку «Места назначения».

3. Выберите «Параметры» > «Новое место назначения» в меню «Места назначения».

4. Задайте имя для места назначения.

5. Создайте ссылку HTML, которая указывает на это место назначения, добавив #[имя-места-назначения] в конец ссылок URL.

Например, этот тег HTML открывает папку с именем «glossary» в файле PDF myfile.pdf:

Источник

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.

Читайте также:  Get all results mysql php

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:

Screenshot--14-

  • 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.

Screenshot--15-

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:
        

Screenshot--16-

  • 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.

Читайте также:  How to update java version

Similar to the previous methods, the syntax can be understood by this example:

Screenshot--16-

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!

Источник

Оцените статью