Introduction to PDF
The full name of PDF is Portable Document Format (PDF). The display of this format has nothing to do with the operating system, resolution, equipment and other factors. Whether it is in Windows, Unix or Apple's Mac OS operating system, the PDF format is Universal. Created by Adobe in 1993 for document transfer, this format uses the PostScript page description language and is suitable for printing images and text (whether on paper, film, or non-physical CRT). PDF is based on page description language. It can not only be as readable as program code, but also represent vector graphics that can be enlarged and reduced arbitrarily.
The PDF file format can encapsulate text, fonts, formats, colors, and graphics images independent of device and resolution in one file. The format file can also contain electronic information such as hypertext links, sounds and moving images. Documents, integration and security reliability are high.
Why PDF files are so popular
Many people complain that PDF can neither be edited nor copied, nor can it be directly converted into Word. Why use PDF to transfer data?
As everyone knows, the shortcomings of everyone's complaints are caused by the fact that its advantages are too powerful.
The original purpose of PDF was to adapt to the printing industry of paper media. PDF wasn't originally a document standard designed for e-reading on small screens, it came from print - typesetting based on paper size. We can think of it as an electronic version of a paper document, not electronic text, but electronically printed paper. The purpose of its existence is to achieve accurate batch printing, to ensure that the relative position of the file format can be saved in multiple screens, multiple systems, and multiple terminals, and the display layout will not appear disordered, ensuring the format printed on the paper. Exactly consistent, without content formatting.
Just imagine, if we need to print an insurance subscription book, the format of the PDF file printed by the insurance business personnel using the iPad is very different from the file format printed by the PC computer, the number of pages is inconsistent, and the line breaks are inconsistent, how to guarantee the legal insurance subscription book? effect. A policy can come in many formats, and it's impossible to trust any one policy. Just as you have multiple clocks in front of you, we can't get the current exact time.
If you have implemented functions such as printing pages, printing forms, etc., you may have a deep understanding of the pits, and only you know the hardships you have suffered.
Because saving a web page as a PDF for users to preview or download is a good way to ensure that the format is consistent across terminals.
In addition, the advantages of PDF are not only cross-platform and high compatibility, but also the viewing cost to the greatest extent. users do not need to install a heavy and full-featured Adobe to read PDF files. You can view the PDF content using the browser. This means that end users can open PDF files anytime, anywhere, whether they are mobile phones iOS, Android, or old PCs, and new PCs can read PDF files in a variety of ways, rather than Excel files that must be read by Office .
Coupled with the fact that PDF can also be edited in a small range, the setting of security attributes, such as encryption, encrypted printing and other functions, the practicality has also risen to another level.
Front-end generation of PDF file application scenarios
With the development of the mobile Internet, the growth demand of mobile phones has skyrocketed. The more Internet systems, the more new systems are applied to solve users more conveniently and quickly, and the needs of users have also changed quietly with the development of technology.
In the stage of "all people are netizens", it is no longer an era when basic functions can be met, and user experience and interaction needs are more urgent, making it easier to use from the design of the machine age to the humanized design.
The technical architecture of the front-end and back-end separation is smooth, allowing professional people to do professional things, and the development is more efficient and smooth. Therefore, the need to generate and display PDF files in the front-end is also relatively common. We summarize the common application scenarios of PDF:
- Preview PDF files in projects and provide search capabilities
- Mobile phone preview PDF file
- The user fills in the form, generates a PDF file, and the user directly downloads and saves
- Generate PDF contract online, print
briefly summarizes the three types of requirements for generating PDF :
- Online preview, directly open the existing PDF file to browse the confirmation information.
- Realize online generation of PDF files, and instantly generate personalized PDF files for users to view or download according to the user's contextual information, such as newly submitted form information, customer information, purchasing information, etc.
- Print, print existing or generated PDF files directly.
It is a very common requirement to generate PDF files at the front end, and almost all systems with complex business will have such requirements.
Difficulties in front-end generation of PDF files
The difficulty of generating PDF files on the front-end is that the front-end is purely dependent on the client's browser resources, the available resources are limited, and the terminals are diverse, which makes it more difficult to generate PDFs than the server. Take the ActiveReportsJS front-end report control as an example, which provides the front-end PDF export capability, but before exporting PDF files, we need to pay attention to the following issues:
- ActiveReportsJS component is a front-end control, and the overall operation is based on the Web browser environment.
- The desktop report designer is based on Electron and uses Chromium to display the user interface.
- A Web application that runs in a browser on a user's computer with the Web Online Designer and Report Viewer components.
- PDF, Excel and HTML are used as generators to measure and generate report content based on the browser environment.
- Reports consist of textual content, and the browser renders font shapes based on glyphs. Font resources contain information that maps character encodings to the glyphs that represent those characters. Therefore, the browser needs to access the correct font resource in order to be able to display the text as expected.
Therefore, there are three big mountains to overcome in generating PDF on the front end:
- browser. There are hundreds of browsers, but the number of mainstream browsers is not bad, but there are only three or four, such as Chrome, FireFox, Safari, Edge, browsers, and of course the domestically dominant 360 browser. Each browser handles text content and even CSS properties inconsistently, and because each has its own standards, we can use all functions normally in Chrome, but when Firefox uses PDF, the content cannot be displayed normally, but Printing functions normally.
- resolution. If you want to list all the resolutions in the world, I am afraid that one piece of A3 paper cannot be completely output. If the web page rendered based on Dom encounters terminals with large differences in resolution, the problem of zooming in and out cannot be solved at all.
- font. Unicode characters such as English and numbers can ensure the normal display of the PDF, but if the page contains Chinese characters, it is drawn based on the glyph when generating the PDF. If the provided glyph is inconsistent with the glyph displayed on the actual page, it is not necessary to generate a PDF. The effect of seeing what you get may be a catastrophic problem for some files with strict format requirements, accurate to newline characters, number of lines, margins, etc. Therefore, providing the correct font is also the most important when PDF generation is to ensure the format is consistent. a little.
Commonly used front-end methods for generating PDF files
method one
html2canvas + jsPdf converting HTML to image, convert the image to PDF file
Applicable scenarios: applicable to single-page PDF files, and the terminal equipment is the same
Sample code:
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
})
shortcoming:
- The generated PDF file is composed of pictures, the content cannot be copied, and it is not clear after enlargement
- The pagination print position cannot be controlled
Method Two
jsPDF generates PDF files directly based on Dom objects
jsPDF , support adding page numbers
Applicable scenarios: Suitable for simple page layouts, such as conventional two-dimensional tables, but complex report styles define Dom elements, which are extremely complicated to use.
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#content')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}, margins);
}
</script>
shortcoming:
- There are differences in the display between multiple platforms, such as the Dom structure displayed on the mobile phone and the layout on the computer are very different
- Poor support for Chinese, Japanese and Korean fonts, garbled characters will appear
- Layouts vary across browsers
Method three
Use ActiveReportsJS to design layouts directly online and generate PDF files directly
Advantages: Simple and easy to use, visual operation, what you see is what you get, less code, suitable for multiple platforms, ensuring the consistency of the three terminals of PC, Web and mobile.
Disadvantages: It needs to be matched with corresponding fonts, which can meet the needs of accurate PDF generation. It is suitable for industries such as insurance, finance, testing and other industries that require strict PDF file formats.
Font information usually contains:
- Font Name: Font ID such as Arial, Calibri, or Times New Roman
- Font style: normal or italic
- Font Weight: Thin, Thin, Normal, Medium, Bold, Thicker
- A font family usually consists of multiple fonts, usually represented by separate files.
Next, let's take a look at the specific implementation process.
Applications that display reports in the Report Viewer, export reports to PDF, or host the Report Designer component should use the same configuration that was created for the standalone designer application. The easiest way is to copy the Fonts folder and fontsConfig.json file to the assets folder of the project. This folder varies for different front-end frameworks. Examples are as follows:
The RegisterFonts method is an asynchronous function and returns a Promise object. Code that calls this method can also wait until the Promise result is returned before loading or exporting the report in the Viewer component.
{
"name": "Montserrat",
"weight": "900",
"style": "italic",
"source": "assets/Fonts/Montserrat/Montserrat-BlackItalic.ttf"
}
<script src="https://cdn.grapecity.com/activereportsjs/2.latest/dist/ar-js-core.js"></script>
<script>
GC.ActiveReports.Core.FontStore.registerFonts(
"/resources/fontsConfig.json" // replace the URL with the actual one
)
</script>
var pageReport = new ARJS.PageReport();
pageReport.load('Quotation.rdlx-json')
.then(function() { return pageReport.run() })
.then(function(pageDocument) { return PDF.exportDocument(pageDocument, settings) })
.then(function(result) { result.download('arjs-pdf') });
HTML display renderings:
PDF display renderings:
Reference example: https://demo.grapecity.com.cn/activereportsjs/demos/api/export/purejs
This article introduces you to three different ways to realize various PDF printing methods, and will bring you more interesting content in the future~ If you feel good, give it a like and go.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。