Rectangle 27 30

Otherwise, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.

DOMPDF : PHP class that wraps the HTML and builds the PDF. Works good, customizable (if you know PHP), based on pdflib, and, if I remember correctly, it takes even some CSS. Bad news: slow when the HTML is big or very complex.

HTML2PS: same as DOMPDF, but this one converts first in .ps (GhostScript), then, in whatever format you need (PDF, JPEG, PNG). For me it is a little better then DOMPDF, but have the same speed problem. Oh, better compatibility with CSS.

Those two are PHP classes, but if you can install some software on the server, and access it through passthru() or system(), give a look to these too:

wkhtmltopdf: based on WebKit (Safari's wrapper), it's really fast and powerful. Seems like it is the best one (at the moment) for HTML to PDF conversion on the fly, taking only 2 seconds for a 3 page XHTML document with CSS2. It's a recent project anyway, so the google.code page is often updated.

htmldoc : this one is a tank, it really never stops/crashes. The project seems dead, as of 2007, but if you don't need CSS compatibility this can be nice for you.

tcpdf - this is an enhanced and maintained version of fpdf. It has all the main Features of tpdf and it also has faster execution time with great output. For detailed tutorial on using the two most popular PDF generation classes: TCPDF and FPDF, please follow this link. I think you should continue using TCPDF.

See these posts also:

PDF Export in php - Stack Overflow

php pdf formatting export converter
Rectangle 27 3

Else, if you want to convert an HTML page in pdf via PHP, the options I know are:

DOMPDF : php class that wrap the html and build the pdf. Works good, customizable (if you know php), based on pdflib, if i remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same of DOMPDF, but this one convert first in .ps (ghostscript), then, in whatever format you need (pdf, jpg, png). For me this is little better than dompdf, but have the same speed problem.. oh, better compatibility with css.

Those two are php classes, but if you can install some software on the server, and access it through passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seem like is the best one (atm) for convert on the fly html pages to pdf, taking only 2 seconds for a 3 pages xHTML document with CSS2. Is a recent project, anyway, the google.code page is often updated.

htmldoc : this one is a tank, it really never stop/crash.. the project seem death in the 2007, but anyway if you don't need css compatibility this can be nice for you.

tcpdf - this is an enhanced and maintained version of fpdf. Main Features of tcpdf and it is also having less execution time with great output. For a detailed tutorial on using the two most popular pdf generation classes: TCPDF and FPDF. Please follow this link.

mysql - How to convert html into pdf with php? - Stack Overflow

php mysql html pdf download
Rectangle 27 2

We have recently finished an implementation of the Daisy CMS, and we have been very pleased with it. It's a database-backed document repository with a Wiki front end. Daisy is very customizable, is open source (runs on the Java stack), and has some great features out of the box, such as:

Mike do you know how Daisy stores it files ? Are you generating new content using the Wiki and then exporting to HTML and PDF ?

Daisy stores the content as XML files in the database (MySQL by default). The Wiki queries the document repository, retrieves the XML, and uses XLST to convert the documents to HTML. For export, it uses another set of XSL files to generate either static HTML or PDF. This allows you to style the content differently, based on whether you're viewing it from the live Daisy site, or as static HTML, or as a PDF. You can also setup an arbitrary number of Wiki 'sites' that provide different views of the same repository. We have an internal site and a customer site, for example.

I should add that the reason we chose Daisy was because the potential for content reuse was huge. We are translating our documentation into several languages, and so being able to reuse content in different contexts, instead of copying and pasting all over the place, dramatically reduced our translation and review costs, and improved content consistency across the enterprise.

Building a Documentation System - Stack Overflow

documentation documentation-generation
Rectangle 27 1

I've been using PrinceXML to do exactly what you're talking about, the downside to it is that you have to install it on your computer with a shell script.

A colleague and I are working on a simple app that is basically an html text editor but can export the html as a PDF, with a table of contents, footnotes running heads and all.

Prince is the best we've come across so far. Let me know if this is not something that will work for you.

You can do the same things for less money with wktmltopdf and a php wrapper..

The problem we had with it is that it isn't supported on the mac yet...

Use a little vps server ? It is cheaper than a PrinceXml licence and you can do what you want...

And what about a Virtual Machine ? It's a little bit loud just for this, but it's offline, cheap and easy to use.

javascript - Printed HTML per-page footnotes - Stack Overflow

javascript html css css3 css-gcpm
Rectangle 27 1

Instead of downloading you could use a html to pdf converter like wkhtmltopdf. Converting a view to pdf is simple as:

res.render('ticket/pdf', {
    'title': 'Ticket #1',
}, function(err, html) {
    if (err) {
        return res.negotiate(err);
    }
    res.setHeader('Content-disposition', 'attachment; filename=myFile.pdf';
    return require('wkhtmltopdf')(html).pipe(res);
});

If you still like to download a view, do the following:

wkhtmltopdf('http://google.com/', { pageSize: 'letter' })
  .pipe(fs.createWriteStream('out.pdf'));

javascript - SailsJs - Export html view to PDF - Stack Overflow

javascript node.js pdf express sails.js
Rectangle 27 20

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>
Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Just an FYI: saving html as an xls file works fine for Excel 2003, but just be aware that the current version of Excel which most people have these days gives a warning when opening the file, and this is not ideal if the download is for a client. Changing the filename and mimetype for xlsx doesn't work at all (I tried!). Like the others, I recommend PHPExcel.

How to export html table to excel or pdf in php - Stack Overflow

php
Rectangle 27 26

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

Thank you Kristof Feys, but when I click on the button I can see 2 windows. one is save to PDF window and one more new window is opening with pdf view, How can I remove PDf view in new window...

Hmmm... when i tested this in jsFiddle i only received the "save to pdf" window. My guess would be that these 2 windows are browser / plugin related...

Yes, In jsFiddle it is getting only SaveTo PDF window, but in Main Application It is getting one more window opened when user click,How can i remove that new window.

As I am unable to reproduce your issue, i can't really debug it either. You could probably try to remove all your javascript plugins used (except jquery & jspdf) and see if it works then. Afterwards you can re add them one by one to see which one produces the error (if my guess is correct and one of these are producing the issue of course) ... Or if you could reproduce the issue on jsFiddle that could help as well :)

$(document).ready(function) and $(function) are identical; learn.jquery.com/using-jquery-core/document-ready just says, "If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form."

jquery - Export HTML page to PDF on user click using JavaScript - Stac...

javascript jquery jspdf
Rectangle 27 7

@Chris Haas has explained very well how to use itextSharp to convert HTML to PDF, very helpful my add is: By using HtmlTextWriter I put html tags inside HTML table + inline CSS i got my PDF as I wanted without using XMLWorker . Edit: adding sample code: ASPX page:

<asp:Panel runat="server" ID="PendingOrdersPanel">
 <!-- to be shown on PDF-->
 <table style="border-spacing: 0;border-collapse: collapse;width:100%;display:none;" >
 <tr><td><img src="abc.com/webimages/logo1.png" style="display: none;" width="230" /></td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
 <tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
 <tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:11px;color:#10466E;padding:0px;text-align:center;"><i>blablabla</i> Pending orders report<br /></td></tr>
 </table>
<asp:GridView runat="server" ID="PendingOrdersGV" RowStyle-Wrap="false" AllowPaging="true" PageSize="10" Width="100%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="false"
   PagerStyle-CssClass="pgr" HeaderStyle-ForeColor="White" PagerStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" DataKeyNames="Document#" 
      OnPageIndexChanging="PendingOrdersGV_PageIndexChanging" OnRowDataBound="PendingOrdersGV_RowDataBound" OnRowCommand="PendingOrdersGV_RowCommand">
   <EmptyDataTemplate><div style="text-align:center;">no records found</div></EmptyDataTemplate>
    <Columns>                                           
     <asp:ButtonField CommandName="PendingOrders_Details" DataTextField="Document#" HeaderText="Document #" SortExpression="Document#" ItemStyle-ForeColor="Black" ItemStyle-Font-Underline="true"/>
      <asp:BoundField DataField="Order#" HeaderText="order #" SortExpression="Order#"/>
     <asp:BoundField DataField="Order Date" HeaderText="Order Date" SortExpression="Order Date" DataFormatString="{0:d}"></asp:BoundField> 
    <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status"></asp:BoundField>
    <asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" DataFormatString="{0:C2}"></asp:BoundField> 
   </Columns>
    </asp:GridView>
</asp:Panel>
protected void PendingOrdersPDF_Click(object sender, EventArgs e)
{
    if (PendingOrdersGV.Rows.Count > 0)
    {
        //to allow paging=false & change style.
        PendingOrdersGV.HeaderStyle.ForeColor = System.Drawing.Color.Black;
        PendingOrdersGV.BorderColor = Color.Gray;
        PendingOrdersGV.Font.Name = "Tahoma";
        PendingOrdersGV.DataSource = clsBP.get_PendingOrders(lbl_BP_Id.Text);
        PendingOrdersGV.AllowPaging = false;
        PendingOrdersGV.Columns[0].Visible = false; //export won't work if there's a link in the gridview
        PendingOrdersGV.DataBind();

        //to PDF code --Sam
        string attachment = "attachment; filename=report.pdf";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/pdf";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        htextw.AddStyleAttribute("font-size", "8pt");
        htextw.AddStyleAttribute("color", "Grey");

        PendingOrdersPanel.RenderControl(htextw); //Name of the Panel
        Document document = new Document();
        document = new Document(PageSize.A4, 5, 5, 15, 5);
        FontFactory.GetFont("Tahoma", 50, iTextSharp.text.BaseColor.BLUE);
        PdfWriter.GetInstance(document, Response.OutputStream);
        document.Open();

        StringReader str = new StringReader(stw.ToString());
        HTMLWorker htmlworker = new HTMLWorker(document);
        htmlworker.Parse(str);

        document.Close();
        Response.Write(document);
    }
}

of course include iTextSharp Refrences to cs file

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.tool.xml;

This code works properly. but i cannot view the pdf file when it is downloaded. what am i doing wrong?

if this code works for you, you should be able to see your PDF after downloading. I would suggest that you post a question with your code to review and see where's the error. Also try to run your code from different browsers and see if you would be able to view the PDF or not.

c# - How to convert HTML to PDF using iTextSharp - Stack Overflow

c# pdf-generation itextsharp xmlworker
Rectangle 27 11

If all you want is a simple excel worksheet try this:

header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);

$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <!--[if gte mso 9]>
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>Sheet 1</x:Name>
                    <x:WorksheetOptions>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                        </x:Print>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>

<body>
   <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';

echo $data;

The key here is the xml data. This will keep excel from complaining about the file.

excel 07 still complains about this

This is not working with windows 10 Microsoft excel 2016

How to export html table to excel or pdf in php - Stack Overflow

php
Rectangle 27 5

Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel

PDF

How to export html table to excel or pdf in php - Stack Overflow

php
Rectangle 27 2

It is technically impossible to simply "convert" a PDF file to HTML. The PDF format is more like a "canvas", where you "place" your text blocks and images, whereas HTML needs either CSS or a lot of tables to "place" the blocks. Moreover, PDF files embed the images, whereas HTML simply calls other files. There are many other examples of differences, but essentially, it's like asking to convert an image or a video with text in it.

You can however read from a PDF file, and then extract the text and images from it, using libraries or other advanced techniques. .Net has a few libraries, for instance : http://forums.asp.net/post/2167442.aspx

If you only need to convert one file once, you can open the pdf file in Illustrator for instance, and then export that in html. Or you can select all the document (ctrl+a), copy it, and paste it in Word, and then save the result in html. It will be far from perfect, but it will be a start.

How to convert PDF to HTML? - Stack Overflow

html pdf file-conversion
Rectangle 27 7

@Chris Haas has explained very well how to use itextSharp to convert HTML to PDF, very helpful my add is: By using HtmlTextWriter I put html tags inside HTML table + inline CSS i got my PDF as I wanted without using XMLWorker . Edit: adding sample code: ASPX page:

<asp:Panel runat="server" ID="PendingOrdersPanel">
 <!-- to be shown on PDF-->
 <table style="border-spacing: 0;border-collapse: collapse;width:100%;display:none;" >
 <tr><td><img src="abc.com/webimages/logo1.png" style="display: none;" width="230" /></td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
 <tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
 <tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:11px;color:#10466E;padding:0px;text-align:center;"><i>blablabla</i> Pending orders report<br /></td></tr>
 </table>
<asp:GridView runat="server" ID="PendingOrdersGV" RowStyle-Wrap="false" AllowPaging="true" PageSize="10" Width="100%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="false"
   PagerStyle-CssClass="pgr" HeaderStyle-ForeColor="White" PagerStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" DataKeyNames="Document#" 
      OnPageIndexChanging="PendingOrdersGV_PageIndexChanging" OnRowDataBound="PendingOrdersGV_RowDataBound" OnRowCommand="PendingOrdersGV_RowCommand">
   <EmptyDataTemplate><div style="text-align:center;">no records found</div></EmptyDataTemplate>
    <Columns>                                           
     <asp:ButtonField CommandName="PendingOrders_Details" DataTextField="Document#" HeaderText="Document #" SortExpression="Document#" ItemStyle-ForeColor="Black" ItemStyle-Font-Underline="true"/>
      <asp:BoundField DataField="Order#" HeaderText="order #" SortExpression="Order#"/>
     <asp:BoundField DataField="Order Date" HeaderText="Order Date" SortExpression="Order Date" DataFormatString="{0:d}"></asp:BoundField> 
    <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status"></asp:BoundField>
    <asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" DataFormatString="{0:C2}"></asp:BoundField> 
   </Columns>
    </asp:GridView>
</asp:Panel>
protected void PendingOrdersPDF_Click(object sender, EventArgs e)
{
    if (PendingOrdersGV.Rows.Count > 0)
    {
        //to allow paging=false & change style.
        PendingOrdersGV.HeaderStyle.ForeColor = System.Drawing.Color.Black;
        PendingOrdersGV.BorderColor = Color.Gray;
        PendingOrdersGV.Font.Name = "Tahoma";
        PendingOrdersGV.DataSource = clsBP.get_PendingOrders(lbl_BP_Id.Text);
        PendingOrdersGV.AllowPaging = false;
        PendingOrdersGV.Columns[0].Visible = false; //export won't work if there's a link in the gridview
        PendingOrdersGV.DataBind();

        //to PDF code --Sam
        string attachment = "attachment; filename=report.pdf";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/pdf";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        htextw.AddStyleAttribute("font-size", "8pt");
        htextw.AddStyleAttribute("color", "Grey");

        PendingOrdersPanel.RenderControl(htextw); //Name of the Panel
        Document document = new Document();
        document = new Document(PageSize.A4, 5, 5, 15, 5);
        FontFactory.GetFont("Tahoma", 50, iTextSharp.text.BaseColor.BLUE);
        PdfWriter.GetInstance(document, Response.OutputStream);
        document.Open();

        StringReader str = new StringReader(stw.ToString());
        HTMLWorker htmlworker = new HTMLWorker(document);
        htmlworker.Parse(str);

        document.Close();
        Response.Write(document);
    }
}

of course include iTextSharp Refrences to cs file

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.tool.xml;

This code works properly. but i cannot view the pdf file when it is downloaded. what am i doing wrong?

if this code works for you, you should be able to see your PDF after downloading. I would suggest that you post a question with your code to review and see where's the error. Also try to run your code from different browsers and see if you would be able to view the PDF or not.

c# - How to convert HTML to PDF using iTextSharp - Stack Overflow

c# pdf-generation itextsharp xmlworker
Rectangle 27 1

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel">
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

How to export html table to excel or pdf in php - Stack Overflow

php
Rectangle 27 7

Here is my spreadsheet-to-pdf script. It works with the new Google Spreadsheet API.

// Convert spreadsheet to PDF file.
function spreadsheetToPDF(id,index,url,name)
{
  SpreadsheetApp.flush();

  //define usefull vars
  var oauthConfig = UrlFetchApp.addOAuthService("google");
  var scope = "https://docs.google.com/feeds/";

  //make OAuth connection
  oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oauthConfig.setConsumerKey("anonymous");
  oauthConfig.setConsumerSecret("anonymous");

  //get request
  var request = {
    "method": "GET",
    "oAuthServiceName": "google",
    "oAuthUseToken": "always",
    "muteHttpExceptions": true
  };

  //define the params URL to fetch
  var params = '?gid='+index+'&fitw=true&exportFormat=pdf&format=pdf&size=A4&portrait=true&sheetnames=false&printtitle=false&gridlines=false';

  //fetching file url
  var blob = UrlFetchApp.fetch("https://docs.google.com/a/"+url+"/spreadsheets/d/"+id+"/export"+params, request);
  blob = blob.getBlob().setName(name);

  //return file
  return blob;
}

I've had to use the "muteHttpExceptions" parameter to know exactly the new URL. With this parameter, I downloaded my file with the HTML extension to get a "Moved permanently" page with my final url ("https://docs.google.com/a/"+url+"/spreadsheets/d/"+id+"/export"+params").

And note that I am in an organization. So I've had to specify its domain name ("url" parameter, ie "mydomain.com").

Hi crewstyle! Your code works ok! My problem was the correct scope https://docs.google.com/feeds/ Thank you very much!

Worked nicely! Had to modify it a bit since I'm not in an organization in cahoots with google, but pretty much worked out of the box. Thanks!!

Nice solution! Some other params you can use are limiting to a particular sheet with a gid= and a selection by specifying a range using row and column indexes e.g. r1=0&c1=0&r2=55&c2=16

@crewstyle. How come when I execute the above code, I get a Failed to authenticate for service: google . I authorized anonymous already.

Export (or print) with a google script new version of google spreadshe...

google-apps-script google-spreadsheet
Rectangle 27 1

Hopefully this can help someone else.

I used ABCPDF to convert the HTML to PDF, and to tell me where the element is, and then I used iTextSharp to put the blank signature field over it.

There were a couple of "gotchas" in this project:

  • ABCPDF was better at converting HTML to PDF because it is more forgiving with non-standard html, and it was better at reading the physical paths when they contained small mistakes like "/" instead of "\".
  • When sending your html to the PDF converter (iTextSharp or ABCPDF), the relative paths need to be changed into physical paths because the converter won't know in which web-site you are running or in which virtual directories to find the images, scripts and stylesheets. (See a converter below that can help with that)
  • ABCPDF was better at interpreting the style sheets, and the end result looked much better with less code.
  • When trying to figure out where ABCPDF placed the fields or tagged elements, bear in mind that after you add the first page, you still have to go into a loop to "chain" or register the rest of the pages, then only will you be able to resolve the field or the tagged element.

Here is a sample project to demonstrate the solution.

The sample html: (notice the abcpdf-tag-visible: true part in the style of the signature field, this will help us to see where the element is placed in the PDF)

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Test Document</title>
</head>
<body>
    <form method="POST">
        Sample Report Data: <br />
        <table style="border: solid 1px red; margin: 5px" cellpadding="5px">
            <tr>
                <td>Field 1:</td>
                <td><input type="text" id="field1" name="field1" value="FIELD1VALUE" /></td>
            </tr>
            <tr>
                <td>Field 2:</td>
                <td><input type="text" id="Text2" value="FIELD2VALUE" /></td>
            </tr>
            <tr>
                <td>Field 3:</td>
                <td><input type="text" id="Text3" value="FIELD3VALUE" /></td>
            </tr>
            <tr>
                <td>Field 4:</td>
                <td><input type="text" id="Text4" value="FIELD4VALUE" /></td>
            </tr>
            <tr>
                <td>Signature:</td>
                <td><textarea id="ClientSignature" style="background-color:LightCyan;border-color:Gray;border-width:1px;border-style:Solid;height:50px;width:200px;abcpdf-tag-visible: true"
                    rows="2" cols="20"></textarea></td>
            </tr>
        </table>       
    </form>
</body>
</html>

Here is a screen shot of the PDF with a blank signature field, opened with Adobe afterwards.

A sample console application to help test out the PDF converters:

namespace ABCPDFHtmlSignatureTest
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;

    using iTextSharp.text;
    using iTextSharp.text.pdf;

    using WebSupergoo.ABCpdf8;

    /// <summary>
    /// The program.
    /// </summary>
    public class Program
    {
        /// <summary>
        /// The file name.
        /// </summary>
        private const string PdfFileName = @"c:\temp\pdftest.pdf";

        /// <summary>
        /// Adds a blank signature field at the specified location.
        /// </summary>
        /// <param name="pdf">The PDF.</param>
        /// <param name="signatureRect">The signature location.</param>
        /// <param name="signaturePage">the page on which the signature appears</param>
        /// <returns>The new PDF.</returns>
        private static byte[] AddBlankSignatureField(byte[] pdf, Rectangle signatureRect, int signaturePage)
        {
            var pdfReader = new PdfReader(pdf);

            using (var ms = new MemoryStream())
            {
                var pdfStamper = new PdfStamper(pdfReader, ms);

                var signatureField = PdfFormField.CreateSignature(pdfStamper.Writer);

                signatureField.SetWidget(signatureRect, null);
                signatureField.Flags = PdfAnnotation.FLAGS_PRINT;
                signatureField.Put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"));
                signatureField.FieldName = "ClientSignature";
                signatureField.Page = signaturePage;

                pdfStamper.AddAnnotation(signatureField, signaturePage);
                pdfStamper.Close();

                return ms.ToArray();
            }
        }

        /// <summary>
        /// The application entry point.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        public static void Main(string[] args)
        {
            var html = GetHtml();

            XRect signatureRect;
            int signaturePage;
            byte[] pdf;

            GetPdfUsingAbc(html, out pdf, out signatureRect, out signaturePage);

            /* convert to type that iTextSharp needs */
            var signatureRect2 = new Rectangle(
                Convert.ToSingle(signatureRect.Left),
                Convert.ToSingle(signatureRect.Top),
                Convert.ToSingle(signatureRect.Right),
                Convert.ToSingle(signatureRect.Bottom));

            pdf = AddBlankSignatureField(pdf, signatureRect2, signaturePage);

            /* save the PDF to disk */
            File.WriteAllBytes(PdfFileName, pdf);

            /* open the PDF */
            Process.Start(PdfFileName);
        }

        /// <summary>
        /// Returns the PDF for the specified html. The conversion is done using ABCPDF.
        /// </summary>
        /// <param name="html">The html.</param>
        /// <param name="pdf">the PDF</param>
        /// <param name="signatureRect">the location of the signature field</param>
        /// <param name="signaturePage">the page of the signature field</param>
        public static void GetPdfUsingAbc(string html, out byte[] pdf, out XRect signatureRect, out int signaturePage)
        {
            var document = new Doc();
            document.MediaBox.String = "A4";
            document.Color.String = "255 255 255";
            document.FontSize = 7;

            /* tag elements marked with "abcpdf-tag-visible: true" */
            document.HtmlOptions.AddTags = true;

            int pageId = document.AddImageHtml(html, true, 950, true);
            int pageNumber = 1;

            signatureRect = null;
            signaturePage = -1;
            TryIdentifySignatureLocationOnCurrentPage(document, pageId, pageNumber, ref signatureRect, ref signaturePage);

            while (document.Chainable(pageId))
            {
                document.Page = document.AddPage();
                pageId = document.AddImageToChain(pageId);

                pageNumber++;
                TryIdentifySignatureLocationOnCurrentPage(document, pageId, pageNumber, ref signatureRect, ref signaturePage);
            }

            pdf = document.GetData();
        }

        /// <summary>
        /// The try identify signature location on current page.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="currentPageId">The current page id.</param>
        /// <param name="currentPageNumber">The current page number.</param>
        /// <param name="signatureRect">The signature location.</param>
        /// <param name="signaturePage">The signature page.</param>
        private static void TryIdentifySignatureLocationOnCurrentPage(Doc document, int currentPageId, int currentPageNumber, ref XRect signatureRect, ref int signaturePage)
        {
            if (null != signatureRect) return;

            var tagIds = document.HtmlOptions.GetTagIDs(currentPageId);

            if (tagIds.Length > 0)
            {
                int index = -1;
                foreach (var tagId in tagIds)
                {
                    index++;
                    if (tagId.Contains("ClientSignature"))
                    {
                        var rects = document.HtmlOptions.GetTagRects(currentPageId);

                        signatureRect = rects[index];
                        signaturePage = currentPageNumber;

                        break;
                    }
                }                
            }
        }

        /// <summary>
        /// The get html.
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetHtml()
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ABCPDFHtmlSignatureTest.HTMLPage1.html"))
            {
                if (null == stream)
                {
                    throw new InvalidOperationException("Unable to resolve the html");
                }

                using (var streamReader = new StreamReader(stream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
    }
}

When running inside the web server and still generating the HTML, you can use this class to change the relative (virtual) paths to physical (UNC) paths:

namespace YourNameSpace
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Web;

    /// <summary>
    /// Replaces all uris within in an html document to physical paths, making it valid
    /// html outside the context of a web site. This is necessary because outside the
    /// context of a web site root folder, the uris are meaningless, and the html cannot
    /// be interpreted correctly by external components, like ABCPDF or iTextSharp. 
    /// Without this step, the images and other 'SRC' references cannot be resolved.
    /// </summary>
    public sealed class HtmlRelativeToPhysicalPathConverter
    {
        #region FIELDS

        /// <summary>
        /// The _server.
        /// </summary>
        private readonly HttpServerUtility _server;

        /// <summary>
        /// The _html.
        /// </summary>
        private readonly string _html;

        #endregion

        #region CONSTRUCTOR

        /// <summary>
        /// Initialises a new instance of the <see cref="HtmlRelativeToPhysicalPathConverter"/> class.
        /// </summary>
        /// <param name="server">
        /// The server.
        /// </param>
        /// <param name="html">
        /// The html.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// when <paramref name="server"/> or <paramref name="html"/> is null or empty.
        /// </exception>
        public HtmlRelativeToPhysicalPathConverter(HttpServerUtility server, string html)
        {
            if (null == server) throw new ArgumentNullException("server");
            if (string.IsNullOrWhiteSpace(html)) throw new ArgumentNullException("html");

            _server = server;
            _html = html;
        }

        #endregion

        #region Convert Html

        /// <summary>
        /// Convert the html.
        /// </summary>
        /// <param name="leaveUrisIfFileCannotBeFound">an additional validation can be performed before changing the uri to a directory path</param>
        /// <returns>The converted html with physical paths in all uris.</returns>
        public string ConvertHtml(bool leaveUrisIfFileCannotBeFound = false)
        {
            var htmlBuilder = new StringBuilder(_html);

            // Double quotes
            foreach (var relativePath in this.GetRelativePaths(htmlBuilder, '"'))
            {
                this.ReplaceRelativePath(htmlBuilder, relativePath, leaveUrisIfFileCannotBeFound);
            }

            // Single quotes
            foreach (var relativePath in this.GetRelativePaths(htmlBuilder, '\''))
            {
                this.ReplaceRelativePath(htmlBuilder, relativePath, leaveUrisIfFileCannotBeFound);
            }

            return htmlBuilder.ToString();
        }

        #endregion

        #region Replace Relative Path

        /// <summary>
        /// Convert a uri to the physical path.
        /// </summary>
        /// <param name="htmlBuilder">The html builder.</param>
        /// <param name="relativePath">The relative path or uri string.</param>
        /// <param name="leaveUrisIfFileCannotBeFound">an additional validation can be performed before changing the uri to a directory path</param>
        private void ReplaceRelativePath(StringBuilder htmlBuilder, string relativePath, bool leaveUrisIfFileCannotBeFound)
        {
            try
            {
                var parts = relativePath.Split('?');
                var mappedPath = _server.MapPath(parts[0]);
                if ((leaveUrisIfFileCannotBeFound && File.Exists(mappedPath)) || !leaveUrisIfFileCannotBeFound)
                {
                    if (parts.Length > 1)
                    {
                        mappedPath += "?" + parts[1];
                    }
                    htmlBuilder.Replace(relativePath, mappedPath);
                }
                else
                {
                    /* decide what you want to do with these */
                }
            }
            catch (ArgumentException)
            {
                /* ignore these */
            }            
        }
        #endregion

        #region Get Relative Paths
        /// <summary>
        /// They are NOT guaranteed to be valid uris, simply values between quote characters.
        /// </summary>
        /// <param name="html">the html builder</param>
        /// <param name="quoteChar">the quote character to use, e.g. " or '</param>
        /// <returns>each of the relative paths</returns>
        private IEnumerable<string> GetRelativePaths(StringBuilder html, char quoteChar)
        {
            var position = 0;
            var oldPosition = -1;
            var htmlString = html.ToString();
            var previousUriString = string.Empty;

            while (oldPosition != position)
            {
                oldPosition = position;

                position = htmlString.IndexOf(quoteChar, position + 1);

                if (position == -1) break;

                var uriString = htmlString.Substring(oldPosition + 1, (position - oldPosition) - 1);

                if (Uri.IsWellFormedUriString(uriString, UriKind.Relative)
                    && uriString != previousUriString
                    /* as far as I know we never reference a file without an extension, so avoid the IDs this way */
                    && uriString.Contains(".") && !uriString.EndsWith("."))
                {
                    yield return uriString;

                    /* refresh the html string, and reiterate again */
                    htmlString = html.ToString();
                    position = oldPosition;
                    oldPosition = position - 1; /* don't exit yet */

                    previousUriString = uriString;
                }
            }
        }
        #endregion

    }
}

You can use the class like this:

var html = textWriter.ToString();

// change relative paths to be absolute
html = new HtmlRelativeToPhysicalPathConverter(server, html).ConvertHtml();

c# - How do I create a blank PDF signature field using an HTML input d...

c# pdf pdf-generation digital-signature html-to-pdf
Rectangle 27 70

Far and away, the cleanest, easiest export from tables to Excel is Jquery DataTables Table Tools plugin. You get a grid that sorts, filters, orders, and pages your data, and with just a few extra lines of code and two small files included, you get export to Excel, PDF, CSV, to clipboard and to the printer.

$(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

So, quick to deploy, no browser limitations, no server-side language required, and most of all very EASY to understand. It's a win-win. The one thing it does have limits on, though, is strict formatting of columns.

If formatting and colors are absolute dealbreakers, the only 100% reliable, cross browser method I've found is to use a server-side language to process proper Excel files from your code. My solution of choice is PHPExcel It is the only one I've found so far that positively handles export with formatting to a MODERN version of Excel from any browser when you give it nothing but HTML. Let me clarify though, it's definitely not as easy as the first solution, and also is a bit of a resource hog. However, on the plus side it also can output direct to PDF as well. And, once you get it configured, it just works, every time.

UPDATE - September 15, 2016: TableTools has been discontinued in favor of a new plugin called "buttons" These tools perform the same functions as the old TableTools extension, but are FAR easier to install and they make use of HTML5 downloads for modern browsers, with the capability to fallback to the original Flash download for browsers that don't support the HTML5 standard. As you can see from the many comments since I posted this response in 2011, the main weakness of TableTools has been addressed. I still can't recommend DataTables enough for handling large amounts of data simply, both for the developer and the user.

DataTables is fully Javascript. Just the TableTools element uses Flash, and it's miniscule. I would NEVER use Flash willingly in any of my products!

I understand, and I agree. But still - however minuscule - there's a .swf object there, and it cannot run without Flash.

Such a great a solution, but such a shame it needs Flash.

@PramodGaikwad, no, Datatables would replace NG-table. They are effectively the same functionality, but Datatables is FAR more mature and has many, many more features. There is a spinoff of Datatables created specifically for Angular: l-lin.github.io/angular-datatables/#/welcome

javascript - How can I export tables to excel from a webpage - Stack O...

javascript jquery html css table
Rectangle 27 2

Firstly, according to the Model-View-Controller paradigm, a downloadable PDF is a view - so review the Django PDF documentation.

If you are looking at including a Google map in the PDF, there are 3 options:

  • Render on the client, have them print to PDF. This relies on the user actually knowing how to do this.
  • Use a headless browser to pre-render the page using Javascript, return it to Django, then export as PDF. This will be difficult depending on the server.
  • Use the Google Maps Static Map API to generate the image and use that in a tool like Pisa . This has fewer features than the full API, but is ideal for making printable static images. Do this.

As stated in the bottom of the Django Docs on generating PDFs, Pisa works by taking the HTML page and then creates a PDF from that, I've used it before and it means you can use Django templates to construct the page, then instead of returning it, run it through a HTML-to-PDF processor. You would need to just capture this generated PDF and attach it to an email as required.

The above still stands, except for the part about PDFs being views. Regardless, the Static Maps API should give you the images need to include in the Raw HTML you transform into the PDF.

@ Lego Stormtroopr, thanks for the input. For your suggestion #3, can you please expand on how this would work? I am unclear on when and where (in a view?) I would generate the images, and the process of including it in the Raw HTML. Would I be using Reportlab, or wkhtmltopdf in this workflow?

python - How to turn fully rendered html page using Django into PDF - ...

python django pdf wkhtmltopdf
Rectangle 27 3

It works in export to PDF, but not elsewhere is because page based outputs obey page breaks.

HTML is not page based. HTML breaks on interactive page height.

I understand what you mean technically. But SSRS has a paging control, that seems to work on every other report. When I compare two reports I can not find why one pages and the other does not.

reporting services - SSRS report not obeying page breaks - Stack Overf...

reporting-services reportingservices-2005
Rectangle 27 6

In the end, I ended up having to ditch both my original answer and the callbacks criteria due to the unacceptable security risks. In my case, I wrote controller code rendering the report as HTML to a byte array and from there to a FileContentResult that MVC was kind enough to render as a static HTML page. Exporting as PDF, Excel, or any other options will eventually be implemented in a similar method by changing the Render parameter from HTML4.0 to whatever is appropriate (PDF,XLS) and the MIME type. This approach works with SQL Server 2008R2 and beyond. I haven't tried it with previous versions of SQL Server.

[OutputCache(Duration = 120, VaryByParam = "id")]
public ActionResult ExportHTML(int id)
{
    // we need to add code to check the user's access to the preliminary report.
    // Also need to consolidate code between ExportHTML and ExportPDF.
    var userid = <userid>;
    var password = <password>;
    var domain = <domain>;
    IReportServerCredentials irsc = new myApp.Models.CustomReportCredentials(userid,
        password, domain);
    var parametersCollection = new List<ReportParameter>();
    parametersCollection.Add(new ReportParameter("Snapshot", id.ToString(), false));
    ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
    rv.ProcessingMode = ProcessingMode.Remote;
    rv.ServerReport.ReportServerCredentials = irsc;
    rv.ServerReport.ReportPath = <reportpath>;
    rv.ServerReport.ReportServerUrl = new Uri("http://localhost/ReportServer");
    rv.ServerReport.SetParameters(parametersCollection);

    rv.ServerReport.Refresh();
    byte[] streamBytes = null;
    string mimeType = "";
    string encoding = "";
    string filenameExtension = "";
    string[] streamids = null;
    Warning[] warnings = null;

    streamBytes = rv.ServerReport.Render("HTML4.0", null, out mimeType, out encoding,
                                         out filenameExtension, out stream ids,
                                         out warnings);
    var HTMLReport = File(streamBytes, "text/html");
    return HTMLReport;
}

asp.net mvc 4 - How do I render a remote ReportViewer aspx page in MVC...

asp.net-mvc-4 reporting-services webforms reportviewer
Rectangle 27 1

PHPDocx has a solution. According to site you may extract data directly from any database or spreadsheet and export them to other popular formats (PDF, DOC, HTML, ODT, ...) with the help of the conversion plugin. These reports may include editable graphs (only docx), images, tables, headers, footers, etcetera.

Am not sure how good it can convert word to html

You're right - PHPDocx should work for this. Unfortunately you'll need to buy a license in order to get the PHPDocx version that allows DOC/X to HTML.

PHP Convert Word file to HTML without losing styling and images - Stac...

php ms-word docx doc