I have just started using jsPDF for creating PDF. When I am saving it, it generates two PDF files at that time. The first PDF name is the same as I gave in the code but the second PDF name is any text (like: DXTRE5.pdf). I need only one PDF with the given file name. Please help me.
$('#print').click(function () {
var doc = new jsPDF();
var chartHeight = 80;
doc.setFontSize(15);
doc.text(35, 25, "Prospect Report Graph");
$('.myChart').each(function (index) {
var imageData = $(this).highcharts().createCanvas();
doc.addImage(imageData, 'JPEG', 45, (index * chartHeight) + 40, 120, chartHeight);
});
doc.save('reports_graph.pdf');
});
The code looks fine. This won't trigger any PDF export twice. It should be somewhere else where click binding of the #print should exist in your code. Check and find the code you could fix that issue.
That duplicate click binding may have line like doc.save('DXTRE5.pdf'); find and remove that binding.
Related
Using Mr. Rio's pdf generation library as an example for demonstration at https://raw.githack.com/MrRio/jsPDF/master/#
So basically if you copy the code below and paste in the link above you will be able to see what I am talking about. I am attaching the screenshot as well for clarity.
On the sample text myTxt I've two new line so I expect bullet#2 and #3 on new line but it all gets displayed in one line until I click on the textfield and then it recognizes the newline. Is there any solution to this issue or any workarounds?
I've tried using \r\n, \n and \u000a but none of it seems to work.
var { TextField } = jsPDF.AcroForm;
doc.setFontSize(20);
var myTxt = `1. This is my first bullet \
\n2. This is my second bullet \
\n3.A third one`;
doc.text("TextField:", 10, 145);
var textField = new TextField();
textField.Rect = [50, 140, 150, 60];
textField.multiline = true;
textField.value = myTxt;
doc.addField(textField);
I'm using pdfmake to generate a document that contains a number of sub-documents, e.g. a PDF containing invoices; each invoice is a logical document inside the PDF document.
I have a requirement that in the footer or header of each page I show "Page of " where both those numbers are relative to a single invoice, and not the overall document.
The header and footer callbacks look good, but only specify the page number and count relative to the entire document, and the pageBreakBefore callback doesn't generate anything like the documented information, and in any case I can't figure out how I could use it here.
This doesn't seem like a unique requirement, so hopefully I'm just missing something obvious.
Thanks!
I believe that pdkmake's header and footer function's arguments can only contain the global pageCount.
There is however a way to reproduce the behavior that you want, if you handle manually the pageBreaks :
const realPageIndexes = [];
let currSubPdfIdx = 0;
let currPageCountForSubPdf = 0;
const getPageBreak = (newSubPdfIdx: number) => {
if (currSubPdfIdx !== newSubPdfIdx) {
currSubPdfIdx = newSubPdfIdx;
currPageCountForSubPdf = 0;
} else {
currPageCountForSubPdf += 1;
}
realPageIndexes.push(currPageCountForSubPdf);
return {text: '', pageBreak: 'after'}; // return elem causing the pageBreak
}
The footer function, filling the page numbers, is called once the document definition generation is done.
If you handle every overflow by yourself, by calling getPageBreak(currentSubPdfIndex) at the end of each page, you will end up knowing which sub-Pdf is displayed in each page :
I display part of the 1rst subPdf in page 1:
I display the end of 1rst subPdf in page 2
I display 2nd subPdf in page3
I display 3rd subPdf in page4 ....
.
let subPdfIdx = 0;
pdfContent.push(subPdf1FirstPart)
pdfContent.push(getPageBreak(subPdfIdx))
pdfContent.push(subPdf1SecondPart)
pdfContent.push(getPageBreak(subPdfIdx))
subPdfIdx++;
pdfContent.push(subPdf2)
pdfContent.push(getPageBreak(subPdfIdx))
subPdfIdx++;
pdfContent.push(subPdf3)
pdfContent.push(getPageBreak(subPdfIdx))
realPageIndexes[] then looks like :
[ 1, 1, 2, 3 ];
The only step left is to tell the footer function to use the page counts we just created instead of the global page count :
const documentDefinition = {
content: [YOUR CONTENT],
footer: (currPage, allPages) => 'subPdf index is ' + realPageIndexes[currPage];
}
Please note that this method will fail if you don't handle overflows correctly:
if for example a paragraph is too big to fit a page, and you call getPageBreak() after that, pdfmake will automatically create a new page for the end of the paragraph (page which is untracked in our realPageIndexes) and then add the page caused by your getPageBreak() right after the end of the text. So just make sure not to overflow the page :)
How to set pdf font size for table content using jspdf?
setFontSize doesn't work in my case.
Setting font size for text in a table using jspdf-autotable looks like this:
var doc = new jsPDF();
doc.autoTable({html: '#table', styles: {fontSize: 20}})
doc.save("table.pdf");
Edit this: jspdf.plugin.autotable.min.js
Find this part and edit fontSize: textColor:20,halign:"left",valign:"top",fontSize:10,cellPadding:5
the default size is 10 and I change it to 7:
textColor:20,halign:"left",valign:"top",fontSize:7,cellPadding:5
Before printing, make a copy of the table object.
Let's say:
let temporalTable = document.getElementsByClassName("table")[0];
Then apply a style to this object. You can use plain JS functions.
And finally:
html2canvas(temporalTableWithNewStyles)
.then((canvas: any) => {
doc.addImage(canvas.toDataURL("image/jpeg"), "JPEG", 0, 50, doc.internal.pageSize.width, element.offsetHeight / 5 );
doc.save(`Report-${Date.now()}.pdf`);
})
I am trying to use the tcpdf module on silverstripe but it doesn't seem to generate the pdf file.
Below is the class that has the method that should be generating the pdf. The $url_handler part is commented because am not sure how to re-route the request from link $PDFLink to this class.
Any kind of help will be greatly appreciated.
class RaaOrders Extends ReportsModule {
public static $allowed_actions = array (
'pdf'
);
public static $url_handlers = array (
// 'get_pdf' => 'pdf'
);
public function pdf(){
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Print a text
$html = '<span style="background-color:yellow;color:blue;"> PAGE 1 </span>
<p stroke="0.2" fill="true" strokecolor="yellow" color="blue" style="font-family:helvetica;font-weight:bold;font-size:26pt;">You can set a full page background.</p>';
$pdf->writeHTML($html, true, false, true, false, '');
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf->Output('example_001.pdf', 'I');
}
}
I found out that the issue was exactly what I thought it was. Dependencies were not well taken care of because I was doing a manual install.
So I used composer and everything works fine. And you can actually use SS templating to populate the pdf with data, by returning your Objects to the template as shown below.
$pdf = new TCPDF();
$pdf->AddPage();
$vd = new ViewableData();
$str = $vd->customise(ArrayData::create(array('MyVariable'=>'MyValue')))->renderWith('MyTemplateName');
$pdf->writeHTMLCell(0, 0, '', '', $str, 0, 1, 0, true, '', true);
$strContent = $pdf->Output(BASE_PATH.'/tmp/tmp.pdf', 'S');
Call exit when you're done. That's probably the easiest way.
As with most frameworks the output is done elsewhere, after your logic is implemented. Since you are not returning anything, it may give an empty response, or set an error code, etc. Likely interfering with what the pdf library is trying to do. You can avoid that by prematurely exiting (after the pdf library has output a valid response directly to the browser).
I want to upload image in asp.net mvc like this way.I am using input type file for uploading images , its working fine but I want that when user click on this image and select that image , that image would appear on this type of box , how would I do that . I am saving images path in database and putting them on file directory.
I suspect the best bet is to use the HTML5 file API to read the contents of the attached image to display a preview. When the user submits the file you could do the server-side processing as you currently are, store the URL and return to the browser the location of the new image for proper preview. But check the performance of previewing a large image.
The link shows an example of previewing the file. I've copied the code in here as well, but please check the article for better understanding.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>