Monday 11 October 2010

ASP: Create pdf files with FPDF

   


One interesting thing you can do in a web site or application is to present reports directly in pdf format. If you have a database from which you pull data, you can manipulate the information and create a pdf file on the fly. FPDF is a PHP class created by Olivier PLATHEY, but a wise guy named Lorenzo Abbati translated it for asp. The class is completely free for commercial and non commercial use, and has almost everything you need to build up your pdf document. The problem is that Lorenzo has his web page and all the related documentation in Italian. You can always refer to the original PHP version of the class in order to understand in depth how it works. Here I will only scratch the surface and explain the basics.
*** Important Note: it seems that as of the end of November 2011, the site hosting the FPDF library is gone dead. That's quite sad, because of the lost files and related documentation on how to use it. For now, I will leave the links on this page, hoping that they will get back somehow, for reference. If someone would like to host the files or already is distributing the library, please let me know so that I can insert the working link. In the meantime, if you need help, contact me directly, sending me an email. ***
*** Second important note: while the FPDF asp site is waiting to be republished (in January 2012 the site is under construction) one great user named bcsite decided to host the files on www.inforemax.com/fpdf.zip. Many thanks for his/her valuable help! ***

First of all download the class and extract the files in a folder of your web site. The folder (we call it "public") must have read and write permissions: that is because the pdf file will be saved (temporarily) on the server.
Create a new .asp page and insert all the code needed to retrieve eventual data from your database. Then, include the class:
<!--#include virtual="/public/ts/fpdf.asp" -->
At this point we need to initialize the pdf file, setting some parameters:
<%
Set pdf=CreateJsObject("FPDF")
pdf.CreatePDF "P","mm","A4"
pdf.SetPath("fpdf/")
pdf.SetFont "Arial","",12
pdf.Open()
The main difference between the use of the class in VBScript and JavaScript is in the CreateJsObject command, which is used in VBScript. For JavaScript you need to use var pdf = new FPDF();
In our examples we will consider VBScript as our preferred language.
CreatePDF initializes the class with 3 parameters: orientation, measure unit, format. Orientation might be "P" for portrait or "L" for landscape. Measure unit accepts pt (for points), mm (for millimeters), cm (for centimeters) and in (for inches). Format might be A3, A4, A5, Letter, Legal or an bidimensional array containing width and height (expressed in the aforementioned measure unit).
SetPath sets the relative or virtual path of the fpdf folder (where all the includes, extends, fonts and models folders are located).
We use SetFont for setting the font of the document and its size - SetFont(string family [, string style [, float size]]).
Open starts the generation of the document, but at this point nothing is actually produced. We need to start inserting stuff:
pdf.AddPage()
pdf.Image "head.jpg",5,5,201,0
The AddPage() command inserts a new page. It accepts a string orientation in the form of "P" or "L", otherwise it will take the default orientation given by the CreatePDF command.
In the example above, we insert an image called "head.jpg". The command syntax is: Image(stringfile, float x, float y, float w [, float h [, string type [, mixed link]]])
The image types supported are JPG and PNG.
Now we go on and insert new elements:
pdf.SetXY 95,13
pdf.setfillcolor 255,255,255
pdf.Cell 55,5,"HELLO!",1,0,,1
First of all, we set the inserting position to a specific point on the page, with SetXY(float x, float y). Then we set the fill colour with SetFillColor(int r [, int g, int b]) because we want to determine the fill colour of any cell or box created afterwards. Infact we insert a cell with the command Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, int fill [, mixed link]]]]]]]). In the given example the cell is 55 in width, 5 in height, it contains the text "HELLO!", the cell has a border ("1"), it is alligned to the right ("0" right, "1" at the beginning of a new line and "2" at the bottom), default as string aligment (possible values are "L", "C" and "R") and finally the fill must be drawned ("0" would be transparent).
The string can be replaced with anything you like, from a variable to a value of your recordset. You can also use a simple repeated region to display records from a database.

Wow! That was hard! Now let's go on...
pdf.SetXY 8,156
pdf.setfillcolor 197,198,200
pdf.MultiCell 40,4,"Hello!",0,0,1
After changing position and fill colour, we create a MultiCell. A MultiCell has the same parameters as Cell, but it can contain text with line breaks. Those line breaks could be automatic (when the text reaches the cell width) or explicit (with /n). MultiCell(float w, float h, string txt [, mixed border [, string align [, int fill]]]).
As you can see all the objects can be placed whereever you need them to be, and if you use the SetXY command, you don't really need to follow the document natural flow. Infact you can add objects at the end of a page, and afterwards, get back adding an image at the top of it.
After inserting all the needed elements, we can add new pages and elements, but eventually we finish our work. So we close the document and create it:
pdf.Close()
filewrite=Server.MapPath("/public/mypdf.pdf")
pdf.Output filewrite
The close command closes the document (ah!). Then we set the filewrite variable to be used with the Output command. This is the tricky part and I remember I played a lot with it. The Output command is Output([string file [, boolean download]]) where file is the name of the file. If it is left blank the file will be opened by the browser, otherwise saved. If the file is specified, download could be "false" (the file is saved locally) or "true" (a "Save as" dialog will be opened). That gave me a lot of troubles, and so I decided to use the command as in the example. The file is actually saved in the public directory, and that might be a problem if you generate different files with dynamic names: infact your folder might be soon filled up with files you don't really need. So we just use a little trick to open the file in browser and then delete it from the server:
Response.ContentType = "application/x-unknown"
FPath = filewrite
fn = "mypdf.pdf"
Response.AddHeader "Content-Disposition","attachment; filename=" & fn

Set adoStream = CreateObject("ADODB.Stream")
adoStream.Open()
adoStream.Type = 1
adoStream.LoadFromFile(FPath)
Response.BinaryWrite adoStream.Read()
adoStream.Close
Set adoStream = Nothing
dim fs
Set fs=Server.CreateObject("Scripting.FileSystemObject")
    if fs.FileExists(server.mappath("/public/"&fn)) then
      fs.DeleteFile(server.mappath("/public/"&fn))
    end if
set fs=nothing

Response.End
%>
Basically with the above code, we open the pdf file in the browser (obviously a pdf plug-in or reader must be installed in the target computer) and then using the Scripting.FileSystemObject (which I explained in different older posts) we delete it.

I understand that I only explained the basic use of the FPDF class, but I believe that this starting point could make some of you more curious. Please visit the online documentation for further information (but remember it is in Italian).
Let me know what you think about it.

204 comments:

  1. Hi, great info. However I can not make image work. If I include image, I always get this error: File does not begin with '%PDF-'.
    have you tried?

    br
    s

    ReplyDelete
  2. Thanks for the post. I hope there will be a website with a ASP forum. I also found a website at http://www.aspfpdf.com

    ReplyDelete
  3. Thanks very much for your comments.

    For the "Files does not begin..." error, I would like to see the code in order to help you.
    As a start please check the path to your image. That might be the issue.

    ReplyDelete
  4. Example: folder images contains all the image files.

    <%
    pdf.Image("images/logo.jpg"),80,6,50,50
    %>

    first two numbers are the position in mm. The last 2 numbers are the height and width from the image in mm.

    At the moment I use a modified fpdf.asp file. This file is modified by dmxzone.com They use this file for an extension named Universal Data Exporter. If somebody is interested. Let me know.

    Does someone know how to use header and footer in a VBscript ASP page. NOT an Jscript ASP page

    ReplyDelete
    Replies
    1. May you send me the modified fpdf.asp from dmxzone to nicky.echevarria@gmail.com????

      Delete
    2. @StillASP May you send me the modified fpdf.asp from dmxzone to nicky.echevarria@gmail.com?

      Delete
  5. @StillASP: I remember I had the same problem. Put your image in the same folder where the asp file you use to create pdf is. Then change
    <%
    pdf.Image("images/logo.jpg"),80,6,50,50
    %>
    to
    <%
    pdf.Image ("logo.jpg"),80,6,50,50
    %>
    That I believe is a problem of fpdf itself: you can't refer to a folder outside the fpdf folder. Don't know if I made myself clear. If it doesn't work get back to me...

    ReplyDelete
  6. Hi Marco, for me it was not the image problem. It does work for me. To put a image in another folder than the pdf. Maybe it has to do with my modified fpdf.asp file.

    Do you know how to use the header and footer within a VBscript ASP page and NOT an Jscript page

    Maybe it is nice to collect some scripts in ASP like fpdf.org

    ReplyDelete
  7. I'm sorry I don't know anything about the modified fpdf file.

    To create header and footer you could use css quite easily.

    ReplyDelete
  8. Is it possible to autoclose the browser/pdf window AFTER output?

    ReplyDelete
  9. @Henriette:

    When you create the pdf, if you use my code, you save the pdf file on the server, open it in client browser (or Acrobat reader) and then delete it from the server. That is because you don't want to fill up your server disk space with junk. If you close the browser window, the newly created pdf file is lost. To avoid opening the file in browser, just save it to your server and provide a link to open it. Use that with care, because you might end up with many files on the server.
    Again - remember that the file is saved on the server and not locally (on client).

    ReplyDelete
  10. Accented characters are replaced by some strange characters like é

    Does someone know how to encode decode?

    ReplyDelete
  11. @StillASP
    Try to put this at the top of your page:
    <%Response.Charset = "iso-8859-1"%>
    or
    <%Response.Charset = "utf-8"%>

    ReplyDelete
  12. Thanks Marco,

    It works. I had problems with the modified fpdf file I use. Now I downgrade to version 1.0.1 and have no problems with strange characters anymore

    ReplyDelete
  13. @StillASP:

    Just to inform you that soon I will publish a post about creating a footer with VBScript.

    ReplyDelete
    Replies
    1. May you please help me with header and footer in asp fpdf using vbscript

      Delete
    2. No. What's there in the article is all I can say.
      Good luck.

      Delete
  14. Hi Marco,

    I use your output script but I cannot force to download a pdf file.

    I get an download screen but it gives an html type instead of a pdf type.

    My folder images has read/write rights

    Any ideas how this happens

    ReplyDelete
  15. @StillASP:
    Please check the path and the fn variable.
    The images folder should not get in the way. In my example I used a "public" folder with read/write permissions.

    ReplyDelete
  16. Hi Marco,

    To get your script to work. I need a small modification.

    I need to replace:

    adoStream.LoadFromFile(FPath)

    with

    adoStream.LoadFromFile(Server.MapPath("documenten/mypdf.pdf"))

    I don't know why but now the script works.

    ReplyDelete
  17. @StillASP:
    That's alright... That part could change according to where you put the file that creates pdf files.
    Adding the Server.MapPath you are actually indicating that the file is on the site working folder plus documenten/mypdf.pdf.
    Glad you find the solution!

    ReplyDelete
  18. userdefined pagedimensions

    Whats the way to get userdefined Pagedimensions work?

    pdf.CreatePDF "L","mm",array(100,40) doesn't work.

    Only DIN work!

    ReplyDelete
  19. Kaihawaii,
    thanks for your comment. I've been trying to understand the issue all the morning and I found what's the problem.
    Basically the VBScript Array is not passing to the JavaScript function in fpdf.asp.
    I resolved the problem changing my asp page with:
    Dim a
    a = Array(210,297)
    a = Join(a,",")
    pdf.CreatePDF "P","mm",a

    Then I changed the fpdf.asp. Find this snippet:
    this.Error("Unknown page format: " + xformat);
    and change it to
    xformat=xformat.split(",");

    Then everything should be ok!

    ReplyDelete
    Replies
    1. Or just add this line to FPDF source:
      ...
      else
      {
      xformat=(new VBArray(xformat)).toArray(); // *************** line added by me
      this.fwPt=xformat[0]*this.k;
      this.fhPt=xformat[1]*this.k;
      }
      ....

      Delete
  20. Hello,

    Thanks so much for this little tutorial. I have a page generating the pdf and saving it correctly (on my local machine in the inetpub folder for local testing). However, when I add the chunk of code to open it in the browser and then delete the file, it fails. When I try to open it from the dialog box that pops up, it says: "Adobe Reader could not open 'mypdf.pdf' because it is either not a supported file type or because the file has been damanged (for example, it was sent as an email attachment and wasn't correctly decoded)."
    Any suggestions?
    Thanks in advance.
    Geoff

    ReplyDelete
  21. Hey Geoff,
    thanks for your comment.
    It is clear to me that the pdf is not properly created. Please try to generate a very simple pdf (with just one sentence) and check if it works. Then add stuff until you will find what's wrong.

    ReplyDelete
  22. It appears the link to download fpdf.asp doesn't work any more. Does anyone know where I can download this now?

    ReplyDelete
  23. Rs,

    if you contact me by email, I can send it you. It is very small.

    By the way, the link has gone dead just now... It could be that it will be available again in the future (hope so).

    ReplyDelete
  24. how to stop the file from downloading, i want to store the file and server and send it as a email attachment

    ReplyDelete
  25. Nakhuda,

    thanks for your comment. It's the last part of the article I wrote that is dealing with the opening and file deleting. You should look into it and possibily remove it. That will prevent the file from opening. After that you should create a small routine that will send the file as an attachment. Look into my articles list and you'll find a post about using ASP to send email. Add that and you're done.

    ReplyDelete
  26. Thank you very much for quick respond, I’m able to send the mail with attachment, but it also open/download the pdf before sending email, how to prevent from opening in the browser, I’m able to store and send the email as attachment, thanks in advance.

    <%
    Set pdf=CreateJsObject("FPDF")
    pdf.CreatePDF "P","mm","A4"
    pdf.SetPath("fpdf/")
    pdf.SetFont "Arial","",12
    pdf.Open()

    pdf.AddPage()

    pdf.Image Server.MapPath("head.jpg"),5,5,201,0

    pdf.SetXY 0,10
    pdf.setfillcolor 255,255,255
    pdf.Cell 100,5,"HELLO!",1,1,"C",1

    pdf.SetXY 8,156
    pdf.setfillcolor 197,198,200
    pdf.MultiCell 40,4,"Hello!",0,1,1

    pdf.Close()
    filewrite=Server.MapPath("mypdf.pdf")
    pdf.Output filewrite

    Response.ContentType = "application/x-unknown"
    FPath = filewrite
    fn = "mypdf.pdf"
    Response.AddHeader "Content-Disposition","attachment; filename=" & fn

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing

    set mail = server.CreateObject ("CDONTS.Newmail")
    mail.From = "from@mydomain.com"
    mail.To = "to@mydomain.com"
    mail.Subject = "ordering system"
    mail.Body = "ordering systems"
    mail.AttachFile server.mappath(fn)
    mail.BodyFormat = 0
    mail.MailFormat = 0
    mail.Send
    set mail = nothing
    Response.End

    %>

    ReplyDelete
  27. With this part:

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing

    You are actually opening the file. Remove that and see how it goes...

    ReplyDelete
  28. Hello Marco,

    Is there a way I can make pdf of HTML file without converting into image. like converting Print page into PDF. Pls suggest. Awaiting your reply.

    Thks in advance

    ReplyDelete
  29. Noor, you can use HTML code inside an asp page with FPDF. I know there are online services that allow to add a "PDF" icon to your page. If the icon is pressed the content of the page is converted into a PDF. Don't know if that's what you mean.

    ReplyDelete
  30. Marco , what i need is instead of passing an text i will be passing an html string eg.
    "<table border=1 ><tr><td>s.no</td><td>Name</td></tr><tr><td>1</td><td>ASP</td></tr></table>"

    and i want the output in pdf in the form of a table.. is it possible in fpdf.. Kindly let me know..

    ReplyDelete
  31. Noor, why don't you use FPDF commands to create cells?
    See my other article on FPDF especially: http://thewebthought.blogspot.com/2011/07/asp-use-fpdf-to-create-pdf-with-dynamic.html

    ReplyDelete
  32. Marco i am working on fpdf to create cells.. but just want to know the possibility of passing an html string so that i need not redo the coding part.. since it would have been more useful if i could generate pdf by passing an html string..

    ReplyDelete
  33. Noor, you cannot pass HTML strings as far as I know.

    ReplyDelete
  34. Hi Marco, The download link to Lorenzo Abbati doesn't work anymore. The website is offline. Maybe you can host the fpdf files. It still is a great script for creating pdf

    ReplyDelete
  35. Hey StillAsp, it is really a pity the site is gone. I still have the class and the related files, so if someone needs it, just send me an email. For the moment I will not host the files. If someone have it shared, please include the link here, for everyone's benefit.

    ReplyDelete
    Replies
    1. Hi Marco, I can host the fpdf files. Could you please send it to my email at bcsite@yahoo.com

      Delete
    2. I've just sent it to you. Thanks!

      Delete
  36. I can't download the fpdf.asp file, can help??

    ReplyDelete
  37. Chua, please send me an email on the 9th of January and I will send the files... Unfortunately I'm out of office till then...

    ReplyDelete
  38. Thanks Marco giving me the fpdf.asp files.

    Here is the download link for everyone: www.inforemax.com/fpdf.zip

    ReplyDelete
  39. I don't remember, and I think it's not possible. Unfortunately the online guide is offline.

    ReplyDelete
  40. Hi Marco and bcsite, Making text bold:

    pdf.SetFont "Arial","B",14

    family = arial
    style = bold
    size = 14

    for more info visit http://www.fpdf.org/ and then go to mahual

    ReplyDelete
  41. The moment I switched off the pc, I thought it was SetFont... Hooray to Still_Asp!

    ReplyDelete
  42. I would want to create a page header and page footer that will appear on every page. The examples shown in fpdf.org are in php. How can I subclass it and override the Header() method in ASP?

    ReplyDelete
    Replies
    1. bcsite,
      the pdf that I create have headers and footers. I just insert the header as an image at the beginning of every page and a footer at the end. Knowing the height of the header and footer, I set the position of other elements based on that.
      You can see the example (in Italian) from the Way Back Machine here:
      http://web.archive.org/web/20100824043620/http://www.aspxnet.it/public/Default.asp?page=174&idp=62
      ********
      <%@language=javascript%>

      <%

      // Creazione dell'oggetto
      pdf=new FPDF();

      // Ridefinizione delle funzioni
      pdf.Header=function Header()
      {

      this.Image('fpdf.JPG',10,8,33);
      this.SetFont('Arial','B',15);
      this.Cell(80);
      this.Cell(30,10,'Title',1,0,'C');
      this.Ln(20);
      }

      pdf.Footer=function Footer()
      {
      this.SetY(-15);
      this.SetFont('Arial','I',8);
      this.Cell(0,10,'Page '+ this.PageNo()+ '/{nb}',0,0,'C');
      }

      // Main
      pdf.CreatePDF();
      pdf.SetPath("fpdf/");
      pdf.Open();
      pdf.AddPage();
      pdf.SetFont('Times','',12);
      for(i=1;i<=40;i++)
      pdf.Cell(0,10,'Printing line number '+i,0,1);
      pdf.Output();
      %>

      Delete
  43. Hello Marco,
    I work in a while with FPDF but get it but not get the save file on the server. With your approach, I tried everything. Can I file in a binary file store so that he can not at the screen but to send a file.
    I like to hear it Thanks in advance. Eric

    ReplyDelete
    Replies
    1. Eric, in the last part of the article, I explain how to open the pdf and delete it from the server. Remove that part and the pdf file will stay in the folder. Then you can attach it to an email.

      Delete
  44. please some one help me~!!!!how to give microsoft office word as input

    ReplyDelete
    Replies
    1. As I understand you would like to import data from a Word doc and feed it to an ASP page that will produce a PDF. If it's correct, I think you might be able to do it, but I believe it will be quite complicated. I don't know how to get info from a .doc. Anyone can help?

      Delete
  45. how would I use a dynamic QR image to insert???

    ReplyDelete
    Replies
    1. I'm sorry I don't know anything about QG codes. If it's in image you can insert a path to the image in the database and get it from there...

      Delete
  46. Generating a dynamic QR code can be done with Google's chart API. Just plug a few values into the URL and it'll generate a QR code. Obviously there are more steps to figure out how to implement into a pdf, but hopefully this provides a place to start:
    Example:
    https://chart.googleapis.com/chart?cht=qr&chs=75x75&chl=http://thewebthought.blogspot.com/

    Reference:
    http://code.google.com/apis/chart/infographics/docs/overview.html

    ReplyDelete
  47. Does anyone have the manual for reference? I need to have my page break at certain points. Trying to use AddPage to create the next page but it's not working correctly and only creating the first page. Does anyone have a simple example of 2 pages with a page break?? Beating my head against the wall here as I'm sure it's very simple to do.

    ReplyDelete
  48. Disregard my last question, the 2 pages are being created but just not diplayed when calling the PDF in the browser. Good news is that it is working when I view the PDF file directly.

    ReplyDelete
  49. I recently moved a website from a 2003 server to a 2008 server and received an error in basic.asp line 75.

    It turns out the code "& # 65533 ;" (spaces are mine) is in several places through that include file. I did search and replace to remove it and the code worked flawlessly!

    ReplyDelete
  50. Hello Marco,
    I found a subroutine in classic ASP for barcodes.
    I used the call in an ASP page and it works fine, shows me the result on screen.
    I can not implement the same call in FPDF. I did not find useful references, is there a solution?
    thanks
    Carlo

    ReplyDelete
    Replies
    1. Carlo,
      without knowing the barcode subroutine, I cannot be of any help. Is it generating an image or is it drawing the barcode in another way? If it generates an image (jpg, png, gif...), why don't you try to insert that image in the pdf?

      Delete
    2. Builds the bar code using two images, one white and one black in a loop next.
      If you do not create problems I can post the relevant piece of code?
      However, in your opinion there is no way to call a function in FPDF true?
      Carlo

      Delete
    3. When you create your ASP page in order to generate the PDF, you can insert any ASP code in it. For example you can get data from a database, or, I guess, create a barcode image. When your subroutine (which you can insert at the top of the ASP page generating the PDF) saves the barcode image on the server, you can then call that image. I'm sure the output of your barcode sub can be or is saved on the server.
      If you like, just post the link to your barcode sub.

      Delete
    4. Thanks for your interest
      around you the link where I found the routine that I wanted to use
      http://asp.johnavis.com/blog/default.asp?id=17

      Delete
    5. Carlo, I've looked into the barcode subroutine and it is producing a table with tiny images as output. Unfortunately you can't insert a HTML table into a pdf using fpdf. To obtain the same result, you should rewrite the table using cell and multicell fpdf commands. That is obviously at first sight, but I'm quite sure it would be an incredible work to do...

      Delete
    6. Thanks Mark,
      I try and let you know, or alternatively try with the images as you suggested.

      Delete
  51. HI, I've found your tutorial great and very useful so far.

    Has anyone had any luck with using utf8 character, my specific example is a "£".

    I've found lots of examples on the net on how to do this is php but have not managed top get any to work is ASP

    ReplyDelete
    Replies
    1. Chris,

      you need to use entity codes like "& pound;" without the space between the & and pound.
      See the following article: entity codes

      Delete
    2. I tried this originally and it just prints the ascii code as text in the cell/multicell

      Delete
    3. Chris,
      I've tried to use a simple "£" in a PDF I create with FPDF and it actually shows the pound symbol the way I expected. In your case, I suspect that there's something else getting in the way. In my ASP page I do not "force" any UTF8 charset and the £ is coming out correctly.
      As long as I cannot reproduce the issue, I'm afraid I cannot be of any help. However, if you eventually find the solution, please share it with us.

      Delete
    4. thank you for your time trying to help in any respect.

      I did manage to solve it though.

      When not forcing any html content charset it was prefacing the £ with an accented A which I'm sure we have all experienced at some point.

      But by setting the charset via ASP the satdnard characters/symbols where displayed correctly. so simply replace

      "< meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" > "

      with

      <%response.Charset="ISO-8859-1"%>

      Delete
    5. Great Chris! Thanks a lot for sharing that. I hope others will find it useful.

      Delete
  52. Does someone know how to use a image in a cell. I really don't know how to get this done. I only get a image at work like below:

    pdf.Image("../images/picture.jpg"),95,6,25,25,"jpg",""

    But you can't put this in a cell...

    ReplyDelete
    Replies
    1. Still_asp, if I understand correctly what you are asking, here's what I did. I create a multicell, big enough to accomodate the image and place the image over the multicell. That way the image will seem to be inside the cell.
      Hope that helps.

      Delete
  53. Hi Marco,

    I use the images in a repeat region and flags a green image if true and a red image if false.

    I get this done with text that flags green if true and red if false by using:

    <%
    pdf.SetTextColor
    %>



    Do I create a multicell within the repeat region?

    ReplyDelete
    Replies
    1. If you create the multicell in the repeat region you have to dynamically change its position (with an incrementing variable for example), like I explain here.

      Delete
  54. Hi Marco,

    I think that is the answer i am looking for. X- and Y- function

    pdf.GetY()
    pdf.GetX()

    I will give it a try.

    Thanks

    ReplyDelete
    Replies
    1. Yes, that's right. Have a look at the other article about FPDF. It might help you as well...

      Delete
  55. Just so you'll know...the fpdf.asp file on the alternate download site only supports jpeg images. The parsepng function is either missing or never existed in the first place.

    ReplyDelete
    Replies
    1. If anyone has problems with the alternate donwload version of FPDF, please contact me via email and I will send my version which is complete.

      Delete
    2. Hi Marco I need you help, I have a program that just generates png images and need to insert these images (png) in a PDF file, you can provide me the version that you completed?

      Delete
    3. Again... Arenales, FPDF do not support png images. You need to convert them in jpg... I haven't got a "completed" version. Sorry about that.

      Delete
  56. Does anyone knows how to open an existing template in PDF and add a string (such as name and phone number)? With ASP (not FPDI with PHP)
    Thanks,

    ReplyDelete
    Replies
    1. http://www.asppdf.com/ can do it, but it is not free.
      I see there are many .NET component that could update/modify an existing PDF file but nothing for pure ASP.
      I believe the best and easiest way would be to "build" the template every time... which will make the template, not a template anymore :-)

      Delete
  57. The problem is not only the money. It is you need access to install it on the server and most host services won't do it. I think if someone in the comunity good at php could convert FPDI from php to ASP will be great (similar to Lorenzo's work).

    ReplyDelete
  58. Hi,i has try put 'SipariÅŸ'(turkish) in my pdf..but it only show up 'Siparis' in the pdf..may i know wat's go wrong?then i try put 'SipariÅŸ',but it seems like wont encode and dispay same as it is..

    ReplyDelete
  59. Correction for above post:
    Hi Marco,i has try put 'SipariÅŸ'(turkish) in my pdf..but it only show up 'Siparis' in the pdf..may i know wat's go wrong?then i try put "Sipari&# 351;"(Add spacing between # and 3 for visibility at here),but it seems like wont encode and dispay exactly same as it is..

    ReplyDelete
    Replies
    1. Try to add the following at the beginning of your page:
      <%response.Charset="ISO-8859-1"%>
      P.S. Sorry for the late reply.

      Delete
    2. Hi Marco,has try this before,but it wont work...

      Delete
  60. All, I have the following code.
    pdf.Image "myHat.jpg",0,5,212,288,"JPG"

    If I comment out this line, my PDF pulls up.
    If I uncomment out this line, I get the error: File does not begin with '%PDF-'.
    Any ideas?

    ReplyDelete
  61. Replies
    1. What directory should the file in? I've tried everything.

      Delete
    2. What am I'm checking for? Where does the image file need to be at?

      Delete
    3. You need to put it where the asp file generating the pdf is. Usually that error is due to a bad path.

      Delete
    4. OK, image is in the same location of the asp file that is generating the pdf. I have line as pdf.Image "1003_Page_1.jpg",0,5,212,288,"JPG". This is my exact error message "File does not begin with '%PDF-',Local\EWH%qcy(v'd". Can you confirm that this is the correct way of adding the image? Do you have another option for me to write that line? Thanks for the help.

      Delete
    5. Please, see my answer below...

      Delete
  62. File Locations:
    ASP File:
    \\serverHere\folderHere\webroot\system\docs
    Image Location:
    \\serverHere\folderHere\webroot\system\docs

    URL that is produced when image code is commented out:
    https://internalURL/1003/1003.asp?i=260996097

    I'm not sure what I am missing.

    ReplyDelete
    Replies
    1. I know it's annoying, but the problem could be the path or maybe the last part of your code:
      pdf.Image "myHat.jpg",0,5,212,288,"JPG"
      Instead, try and use:
      pdf.Image "myHat.jpg",0,5,212,288
      Check http://www.id.uzh.ch/cl/zinfo/fpdf/doc/index.htm for more help.

      Delete
  63. Is it possible to get a sample code of the asp page that is creating the PDF with an image that works? Anyone? Thanks.

    ReplyDelete
    Replies
    1. Listen,
      your code seems ok. It's difficult to pinpoint the problem as it can be almost anything. When I have to insert a jpg, I just do what you do. The image stays in the same folder where the asp file generating the pdf is. The folder has read and write permission and the pdf is generated in the same folder and deleted after display.
      That's all I can say to help. If anyone else has some other ideas, please share them and help our friend.

      Delete
    2. Hello,
      I've the same problem. I tried everything, but can't to do page with image. Could anybody send me files with code what works correctly?
      PLEASE, I ´m MAD from it :D

      Delete
  64. Hi guys,

    I have no issues about the location of the image e.g., %PDF. However, my issue is my logo doesn't show anything it is completely blank. I put my "logo.jpg" under /fpdf directory. Any idea?

    Thanks in advance!

    ReplyDelete
    Replies
    1. Is the /fpdf folder the same where you put the asp file generating the pdf?
      I keep saying that because is very important.
      If so, check the size you used when inserting the image. At the same time check the position of the image. Change those values and see if the jpg is there and not too small or out of the page...

      Delete
  65. It's a great article. Thanks Marco.
    Only the problem I'm having is with .gif and .png images.
    FPDF error: Unsupported image file type: gif (png).
    I read somewhere a suggestion to include images.asp in fpdf.asp,
    but it didn't solve the problem.
    Is there a way to insert .gif and .png files?
    --Mike.

    ReplyDelete
    Replies
    1. Hi Mike,
      unfortunately FPDF doesn't support gif or png files. As far as I know, it was planned to develop that part, but it was not. I'm quite sure the PHP version does support those files.
      I suggest to use jpg.
      Sorry about that.

      Delete
    2. Thanks Marco.
      Yes, I looked in my version of fpdf.asp, it only checks for (xtype=="jpg" || xtype=="jpeg")
      And in the images.asp png parsing function is empty:
      this._parsePng = function _parsePng(){}
      But I saw somebody was climing that it can handle .png, just can't find it now.
      By the way can you tell where I can find the latest english version of fpdf.asp?

      Delete
    3. There's no English version of the library. If you mean the help file, please see http://www.id.uzh.ch/cl/zinfo/fpdf/doc/index.htm
      As I said, the png function is empty and not developed.
      The latest version of FPDF is available at the top of this page.
      I hope that helps.

      Delete
  66. Hey Developers, just want to give feedback to my post back in 12 June 2012 16:09. It all came down to a security issue with the folder when you get the %PDF error. Again when you remove the line to add an image it worked but for some reason when adding an image I received the error. Please put modify rights along with Read/Write to the folder directory or the webroot directory. Did this and everything worked. Thanks to everyone for their help.

    ReplyDelete
    Replies
    1. Thank you very much for your post!!! You can't imagine how much time did I spend to find the reason why I get this %PDF error... I was browsing Adobe pages, Oracle pages, PHP and ASP pages and all other possible pages with no success. And here thanks to you I found the reason.
      Again thank you very much!
      Regards,
      Jan

      Delete
    2. Jan, you're welcome. I'm glad everything worked for you! Keep on reading the web thought!

      Delete
  67. Good Day.. i saw FPDF 1.52 version, and i like to know if somebody gets this version for asp. because http://www.aspxnet.it/ it´s not longer support.

    ReplyDelete
  68. Hello, i like to know if anyone could help me include new fonts, i see fpdf for asp requires .js font version but i don´t know how to make it..

    many thanks

    ReplyDelete
  69. Guys, I am using this code, but I can not add images to my pdf files. Every time I try to add an image, I get the following message: "Invalid procedure call or argument". This happens when the "write" function is called (basics.asp, line 89). Any ideas what is wrong? Please, it is very important for me to find a solution.

    ReplyDelete
  70. Hi there,
    Does anyone have any information on any limits around using this code?
    I can get it to work perfectly, include text and images, across multiple pages, all good.
    But when the PDF gets big it seems to fail. I am not sure what the limit is - I can produce a 14 page report with 30 images approx thumbnail size fine, but when I increase the data (from the tables and the number of images) I get the message "do you want to Open or Save PDFSurvey_asp (416 bytes) from server?" (and it uses the name of my code file not the name of the pdf) and it just hangs on this prompt.
    I am fairly confident it isn't the code, as it works for small SQL queries, but when I increase the data it is pulling back from the SQL tables AND NOTHING ELSE, it fails. If I break this same data down into smaller sections, it produces each PDF ok, so I am also fairly confident it is not the data causing the problem.
    Any ideas would be GREATLY appreciated as now I have it working, I do not want to look for another solution entirely!
    Many thanks,
    Kiwi Rach

    ReplyDelete
    Replies
    1. Try to get the data from the db before creating the PDF. That could be the problem... Data could get too much time. It's the only thing I can think of.

      Delete
    2. Unfortunately the PDF is being created within a do-while loop (a new table for every survey asset), so not really possible to do all the SQL querying first :(
      Is there any PDF time setting - to give it more time to put the PDF together?
      Thanks,
      Kiwi Rach

      Delete
    3. No, unfortunately there's not such thing as a timeout. Probably it's more related to an IIS setting on the server (query timeout - if memory serves me well).

      Delete
    4. It is definitely to do with the images. I can run a report pulling all the data, but just referencing the images as text, no problem. But as soon as I "pdf.Image" the images (i.e. show them, just as small thumbnails, and yes they do exist to display) that's when I get the problem. If the report is small, e.g. just 25 images say, it works. If the report is bigger, 40 images say, it does not work. I've tried grouping all the images together (rather than spread out across the document) this makes no difference, so it seems to be a limit (time or filesize) on the number of images in the document.
      Sigh!

      Delete
    5. Found it!
      There is an ASP bufferingLimit in IIS.
      The default value is 4194304 which is about 4MB, my pdfs are about 11MB when all images are included.
      I increased the limit and it WORKS!!
      Thanks for your help,
      Kiwi Rach

      Delete
    6. I'm glad it worked. I was somehow on the right track pointing at IIS... Wrong setting :-)

      Delete
  71. Hi Marco (and everyone else),

    I have an issue when creating a PDF containing an image. Straight text PDFs are fine, but when the PDF contains a JPG, the process spins its wheels forever. IIS creates the file as a *.TMP file, but never serves it back to the user. I'm guessing it may be a permissions issue, but nothing I've tried seems to fix it. Has anyone come across this?

    ReplyDelete
    Replies
    1. Tony, it's either a permission issue or a wrong path. I suggest to remove the image and see if it goes. If so it's a path issue. Otherwise it looks like a permission problem. Try to put the image in the same folder and use it from there as well.
      I hope it helps.

      Delete
    2. Hi Marco, thanks for the reply. Even the barest example won't work if it's an image, so it must be permissions regarding the generation of the temp file. I only have one server to test on, and permissions were pre-established before I got stuck with it. I have no idea what they should be set to for proper operation. Can I ask what your user and folders are set to?

      Delete
    3. I forgot to add: if I rename the .TMP file to .PDF, it loads successfully in Adobe.

      Delete
    4. Tony, I've created a folder, named "public" and give full permission to everyone. That' all.
      Another thing: have you closed the PDF in the asp page? "PDF.close" and so on...

      Delete
  72. Gracias por todo, me fue de muchisima ayuda :)

    ReplyDelete
  73. I want to generate repeat region with images, But when using the script below I get an error. Does someone know a solution....

    ADODB.Stream error '800a0bba'
    File could not be opened.
    /includes/images.asp, line 33

    My read/write permissions are fine...



    While ((Repeat1__numRows <> 0) AND (NOT rsRecordset.EOF))

    strName = Replace((rsRecordset("name")), " ", "_")&".jpg"
    pdf.MultiCell 190,50,""&strName&"",1,0,1
    pdf.Image("../images/"&strName&""),10+x,10+y,47,70,"jpg",""

    y = pdf.GetY()
    pdf.SetXY 10,y+10
    Repeat1__index=Repeat1__index+1
    Repeat1__numRows=Repeat1__numRows-1
    rsRecordset.MoveNext()
    Wend

    ReplyDelete
    Replies
    1. I believe you might have a problem with ".
      Looking at the code, you seem to have to many opening and closing ".
      The code for the image should be, for example:
      pdf.Image "head.jpg",5,5,201,0
      So I guess, if you want to use dynamic names, it should be:
      pdf.Image("../images/"&strName&"),10+x,10+y,47,70
      Obviously I don't see how you handle "x" and "y" but I suppose they are incremented in some way...
      I suppose, in any case that the problem is with the ". I don't know if my solution works, but I cannot test it now, so please try and play around with ".

      Delete
    2. I'm not entirely sure on the solution I wrote... But I'm sure it's a " problem. Why don't try to use ' instead?

      Delete
    3. I just thought about a possible workaround. Change the code to:

      strName = "../images/"&Replace((rsRecordset("name")), " ", "_")&".jpg"
      pdf.Image strName,10+x,10+y,47,70

      Delete
  74. Hi Marco,

    Still give the same error

    ADODB.Stream error '800a0bba'
    File could not be opened.

    and refers to file includes/images.asp, line 33

    ReplyDelete
    Replies
    1. It's still a problem of strName.
      FPDF is probably trying to open the file named "strName.jpg" and cannot find it.
      Try to see what's the value of strName with firebug or something else.
      By the way, why are you replacing "_"? Is that correct?

      Delete
  75. Hi there!
    Sorry for the probable silly question, but is it possible to generate the PDF from the HTML generated by the .asp?
    What I'd like to do is generate a pdf report from the html. like a pdf printer would do but server side.
    THanks for the help!

    ReplyDelete
    Replies
    1. No, it's not possible. You have to build the PDF step by step. Sorry about that.

      Delete
  76. I use replacing for names in the database to attach images files at the server...Like Marco Del Corno in the database attaches to a image on the server Marco_Del_Corno.jpg

    If I hardcode:

    strName = "../images/member/Marco_Del_Corno.jpg" the image shows up in the repeated region

    I I use:

    strName = "../images/member/"&Replace((rsLeden("name")), " ", "_")&".jpg" I get the error.

    If I delete .jpg and only use:

    strName = "../images/member/"&Replace((rsLeden("name")), " ", "_") Unsupported image file type: /images/leden/Marco_Del_Corno what I understand because FPDF can't find a jpg file

    ReplyDelete
    Replies
    1. Now it's clear. What you do seems correct. Are you sure all images are there? (too obvious...).
      Look at what you've written: the path to the images is "../images/member/" or "/images/leden/"? Is this the error?
      I've done the same thing in a project, where product images were shown in the PDF in a table, so I'm sure it works. Unfortunatley I cannot fetch the code I used.
      Moreover, try to replace the " " with "_" before. I mean: be sure to build your strName before using it with FPDF. It doesn't make sense, but sometimes small things are important.
      If I find something I will get back to you...

      Delete
    2. Now it's clear. What you do seems correct. Are you sure all images are there? (too obvious...).
      Look at what you've written: the path to the images is "../images/member/" or "/images/leden/"? Is this the error?
      I've done the same thing in a project, where product images were shown in the PDF in a table, so I'm sure it works. Unfortunatley I cannot fetch the code I used.
      Moreover, try to replace the " " with "_" before. I mean: be sure to build your strName before using it with FPDF. It doesn't make sense, but sometimes small things are important.
      If I find something I will get back to you...

      Delete
  77. If repeating a single file it does work. But multiple gives an error

    strName = "../images/member/"&Replace((rsMember("name"))," ","_")&".jpg"

    pdf.MultiCell 190,50,""&strName&"",1,0,1

    pdf.Image strName,10+x,10+y,47,70

    ReplyDelete
    Replies
    1. In the MultiCell do you see the strName?

      Delete
    2. This is the code I use (I have found it!!!) and it does work!
      Set fs=Server.CreateObject("Scripting.FileSystemObject")
      If (fs.FileExists(Server.MapPath("/Catalog/Accessories"&(family.Fields.Item("IMMI").value))))=true then
      pdf.Image "/Catalog/Accessories/"&(family.Fields.Item("IMMI").value),8,topmargin+10+(Repeat2__index*10),0,10
      else
      pdf.Image "/Images/noimg.jpg",8,topmargin+10+(Repeat2__index*10),0,10
      end if
      I hope it helps.

      Delete
  78. Hi Marco,

    Yes it works. Thanks a lot. I don't why this works. Do you? It has something to do with Server.MapPath

    Again thank you.

    ReplyDelete
    Replies
    1. I should have thought it was the Server.MapPath. Shame on me...
      And the two dots before the path:
      not: "../images/"
      but: "/images"

      Well, I am glad it's working now!
      Take care.

      Delete
  79. Hi Marco,

    FPDF keeps me buzzy. How can I use header and footer in a VBScript environment. The example of the existing header/footer is made in ASP/javascript. I like to use header/footer in ASP/VBScript.

    I have two separated questions:

    1. How can I attach a database recordset to an ASP/javascript page. I want use data from a database with FPDF
    2. How can I use header/footer in a ASP/VBScript page. How can I use

    pdf.Header=function Header(){}

    I prefer number 2 because I always work in a ASP/VBScript environment.

    ReplyDelete
    Replies
    1. I've never used the pdf.Header function.
      I've always create headers and footers for every page.
      You can always use a database recordset. If you want you can always store the resulting data in variables (if that makes things easier).
      Otherwise you can use an "outer" repeat region for headers and footers (every page will be create inside this "outer" repeat region).
      I hope it helps.
      Cheers!

      Delete
  80. Hi Marco,

    Nice work!!!

    I work with fpdf (asp) for a couple of years and am very happy with it.

    Also, for reference, everyone can check out the manual for fpdf (php): http://www.fpdf.org/

    ReplyDelete
  81. Hi,
    I have been struggling with the UK £ in being displayed in the PDF as a multi-byte character, i.e. £. Although Chris Swain's solution did not work for me, when I changed:
    <%@ Language=VBScript%> to <%@ Language=VBScript CodePage=28591%>
    it did work. The £ now displays correctly.
    I found this here:
    http://devlibrary.businessobjects.com/BusinessObjectsXIR2/en/en/RAS_SDK/rassdk_com_doc/doc/rassdk_com_doc/BestPractices11.html

    ReplyDelete
  82. Hi Marco

    I was hoping you could help me with displaying an image in my pdf. Here is the code I am using:



    <%

    Set pdf=CreateJsObject("FPDF")
    pdf.CreatePDF "P","mm","A4"
    pdf.SetPath("fpdf/")
    pdf.SetFont "Arial","",12
    pdf.Open()
    pdf.AddPage()
    pdf.SetXY 20,20
    Set fs=Server.CreateObject("Scripting.FileSystemObject")
    If (fs.FileExists(Server.MapPath("public/logo.jpg")))=true then
    pdf.Image Server.MapPath("public/logo.jpg"),1,0,-300
    else
    pdf.setfillcolor 255,255,255
    pdf.Cell 55,5,"no pic",1,0,,1
    end if
    set fs=nothing

    pdf.Close()
    filewrite=Server.MapPath("public/mypdf.pdf")
    pdf.Output filewrite
    Response.ContentType = "application/pdf"
    FPath = filewrite
    fn = "mypdf.pdf"

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing

    Response.End
    %>

    If logo.jpg does not exist, it creates mypdf.pdf fine with the text "no pic". I do not delete mypdf.pdf, just overwrite it each time. If mypdf.pdf does not exist, and logo.jpg does exist then I get this error:

    ADODB.Stream error '800a0bba'

    File could not be opened.

    /agrichem/fpdf/images.asp, line 33

    And the pdf has not been created. If mypdf.pdf does exist and logo.jpg does exist I get an Adobe error "There was a problem reading this document (12)" and the pdf is blank.

    Thank you for any help you can give me.

    John

    ReplyDelete
    Replies
    1. Put the file that creates the PDF in the public folder. Same for the jpg. Then remove the public\ from all the paths.

      Delete
    2. Hi Marco

      Thank you for your reply. I made the changes and still get the same errors. Do you have any other suggestions?

      John

      Delete
    3. The issue is there. It's related to permission and folders. Please check the comments above for possible solutions. In any case I am sure the problem is what I said because I had the same issues.

      Delete
  83. Hi Marco

    I figured it out - I screwed up the images.asp by renaming the pFileName and not completing the job. Everything works great. I really appreciate the work that has gone into this class. Thank you.

    John

    ReplyDelete
  84. Marco,
    if i want a line in the report after displaying each record, what should i use to make that work??

    Thanks.

    ReplyDelete
    Replies
    1. yes, i did try it..i created an empty cell with mixed border set to 1

      pdf.Cell 200,10,"",1,0,0,0

      I do get a line, but at the end of the link i kind of get another vertical line. Any idea why?

      Delete
    2. The end of the link?
      Try to insert something like space in the cell. Maybe it will go away.
      Other way, just insert a vbLine after the cell.

      Delete
  85. sorry not link, but line...there is a small vertical line on the right side of each line..I have found another way...the following works

    pdf.setlinewidth(0.5)
    pdf.line 1,pdf.gety(),200,GetY()


    Is there a function that will allow me to replace the value 200 with maximum value of x on the far right corner??
    200 here was my guesstimation since i could see the line all the way through on my pdf.

    ReplyDelete
    Replies
    1. Glad you found a solution.

      For the right margin consider that you're working with A4 paper size. Consider the width of that page in inches or cm and convert that value to pixels.
      It's the best guess I can think now (consider that I'm looking at my 4 year child who's trying to get ready to sleep!).
      Oh try to use percentage as well. I don't remember if it works but it's worthwhile trying.

      Delete
    2. Thanks for your suggestions and immediate reply as always...you are awesome!!

      Delete
  86. hi Marco,
    I want to embed indic fonts in pdf file, for test purpose when i use calligra font it gives File does not begin with '%PDF-' error otherwise it is fine with core fonts

    pdf.AddFont "calligrapher","","calligra.js"
    pdf.SetFont "calligrapher","",12

    thanks in Advance

    ReplyDelete
    Replies
    1. Hi. Unfortunately I have no experience with personal fonts. However, the "not begin with..." error is almost always related to path. Be sure to put your .js file in the same folder as the rest of the files (especially the asp file creating the PDF). When FPDF looks for a file isnot really smart and it needs to find it in the same folder.
      I hope it will help.

      Delete
    2. Do you have any solution for the case?

      Delete
    3. Do you have any solution for the problem?I am also trying to load a font call "Abadi MT Condensed Light" to create my pdf file in asp classic script but found no way to make it works.

      Delete
  87. Hi Marco,

    I want to create a pdf file including an image from Asp using the FPDF class and code created by Lorenzo Abbati and did not fix any code. But it shows meet unmanaged data type /fpdf/fpdf.asp, row 893. Can you tell me what is wrong with it?

    Thank you so much!

    ReplyDelete
    Replies
    1. Gene,
      I cannot look into the actual line of code in fpdf.asp, however, most the error related to images are due to a wrong path (images have to stay in the same folder where you have the asp file creating the pdf) or wrong file type (use jpg files). I believe in your case is the latter (wrong file type).
      I Hope that helps.

      Delete
    2. Hi Marco,

      Thank you so much you reply me so fast. I think you are right but could not find what is wrong. The following is the detail of code and folder. Would you please help me to check what is wrong by chance.

      Code in main.asp: pdf.Image "copy.jpg",50,50,100,100,"JPG"
      Code in fpdf.asp: Response.BinaryWrite(outB.Read())

      There is a temp file created under the fpdf folder where the image file copy.jpeg is like this: /fpdf/copy.jpeg /fpdf/maim.asp /fpdf/rad1C822.tmp(0KB) /fpdf/fpdf.asp

      Thank you so much.


      Gene

      Delete
    3. Gene,
      it's a problem of the image. Ok, let's narrow down the issue. First of all, be sure to put the copy.jpg file in the same folder where you have main.asp and fdpf.asp are.
      Use this to create the image:
      pdf.Image "copy.jpg",5,5,201,0
      Another thing: why the file is called copy.jpeg? Should be copy.jpg.
      Now if you can create the file, start to play around with the values for the pdf.Image.
      Last: check the jpg is a valid jpg. Try to use another image if needed.

      Delete
  88. good job.. and i have a question, how do to show report pdf in html whitout save it?its possible?

    ReplyDelete
  89. align text to the right??

    ReplyDelete
  90. I wrote this on test.asp:

    <%
    Set pdf=CreateJsObject("FPDF")
    pdf.CreatePDF "P","mm","A4"
    pdf.SetPath("fpdf/")
    pdf.SetFont "Arial","",12
    pdf.Open()
    pdf.SetXY 95,13
    pdf.setfillcolor 255,255,255
    pdf.Cell 55,5,"HELLO!",1,0,,1
    pdf.Close()
    filewrite=Server.MapPath("mypdf.pdf")
    pdf.Output filewrite
    Response.ContentType = "application/x-unknown"
    FPath = filewrite
    fn = "mypdf.pdf"
    Response.AddHeader "Content-Disposition","attachment; filename=" & fn

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing
    dim fs
    Set fs=Server.CreateObject("Scripting.FileSystemObject")
    if fs.FileExists(server.mappath(fn)) then
    fs.DeleteFile(server.mappath(fn))
    end if
    set fs=nothing

    Response.End
    %>

    But when run on host i receive this error

    Microsoft JScript runtime error '800a01ad'

    Automation server can't create object

    /anhtrungqng/fpdf/includes/Basics.asp, line 19

    Can you help me to solve this trouble?
    Thank a lot!

    ReplyDelete
    Replies
    1. You probably need to give appropriate read and write permissions to the output folder. The error seems to be related to that. I suggest to create a new folder called "public" in your site root, give it read and write permissions and change the code accordingly.

      Delete
  91. Marco,

    Thank you for this site - it has been a life saver. I hoping you can help with the importing of a page, I need to attach digital signatures to a pdf. I thought if I created a page with just those signatures, I could import the page and it would have the headers and footers I needed. Any suggestions?

    ReplyDelete
    Replies
    1. Thank for the kind comment.
      To solve your problem I would insert an image (the signature scan) where you need it when you create the PDF.
      You can even choose the jpg based on some variable during the creation.

      Delete
    2. Unfortuneatley, I don't need a picture of signature, I need them to be able to digitally sign the pdf I created using their PKI.

      Will this work if I add it as a jpg?

      Delete
    3. I don't know what you mean by pki. If you can, manipulate the PDF after creation.

      Delete
  92. PKIs are private keys. Adobe PDFs have the ability to allow users to digitally sign the documents. Since I don't know the code to generate the digital signature blocks, I figured I create a document that contained the signatures and import it. That way I could use your header and footer feature. I found FPDI in php - but it makes my head spin. I cannot alter the document afterwards, because this is the document the customer will sign.

    Marco, any help would be greatly appreciated.

    ReplyDelete
    Replies
    1. Sorry, now I understand. Unfortunately you cannot import a PDF with FPDF. You use it to create it. Adding a pki... I don't think it's possible.

      Delete
    2. Thanks for your help, I appreciate it.

      One last hope, have you heard of FPDI is seems to be associated with FPDF files. It allows imports, but it's written in php and I am writing code with classic asp so I don't understand it.

      Thanks again Marco!

      Delete
    3. There's no fpdi asp version. I believe you have to learn php :-) don't ask me because I know nothing about it. Sorry :-(

      Delete
  93. I've been using the ASP version of fpdf for a few years now, its been very useful, but today I think I discovered a problem with one of it commands.

    pdf.write appears to be broken. First time I've ever used it. Example...

    pdf.write 4,"The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog."

    on the PDF I get...

    The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy
    umped over the lazy) Tj ET

    So just wondering if anyone else has noticed this? I would like to use the Write command as part of a HTML parser.

    Thanks
    Glenn

    ReplyDelete
  94. Never discovered such a bug. Anyone can help?

    ReplyDelete
  95. Microsoft VBScript runtime error '800a000d'

    Type mismatch: 'CreateJsObject'

    I keep getting this error. I set read and write permissions in folder as outlined above. Any suggestions? I've setup the folder as outlined.

    Code



    Set pdf=CreateJsObject("FPDF")
    pdf.CreatePDF "P","mm","A4"
    pdf.SetPath("fpdf/")
    pdf.SetFont "Arial","",12
    pdf.Open()

    pdf.AddPage()
    pdf.Image "head.jpg",5,5,201,0

    pdf.SetXY 95,13
    pdf.setfillcolor 255,255,255
    pdf.Cell 55,5,"HELLO!",1,0,,1

    pdf.SetXY 8,156
    pdf.setfillcolor 197,198,200
    pdf.MultiCell 40,4,"Hello!",0,0,1

    pdf.Close()
    filewrite=Server.MapPath("mypdf.pdf")
    pdf.Output filewrite

    Response.ContentType = "application/x-unknown"
    FPath = filewrite
    fn = "mypdf.pdf"
    Response.AddHeader "Content-Disposition","attachment; filename=" & fn

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing
    dim fs
    Set fs=Server.CreateObject("Scripting.FileSystemObject")
    if fs.FileExists(server.mappath("/public/"&fn)) then
    fs.DeleteFile(server.mappath("/public/"&fn))
    end if
    set fs=nothing

    Response.End
    %>

    ReplyDelete
    Replies
    1. It could be anything. It's difficult to know. Check permission and code. Put everything in the "public" folder. And don't forget to include the FPDF files.

      Delete
  96. Hi - it's been requested whether anybody knows how to put headers & footers on if you're using VBScript. Marco has provided a great example using JavaScript, but it can't be called if you're using VBScript (as I suspect most people will be with ASP).

    I've got something working in VBScript if anybody wants it. Be warned - it's not pretty, and I'm not experienced with passing between multiple languages.

    Step 1 - Create function to modify headers & footers
    Essentially what is required is to replace the header() and footer() functions within the pdf object. I wasn't able to do this with VBScript (I have no idea how to rewrite a javascript function from vbscript, if it's possible), but I could create a Javascript function and call that from vbscript. Doing it this way gives javascript access to the pdf object you've created.

    So, either include this script in a file or put it on your page...
    < script language="javascript" runat="server" >
    function redefineElement(thisObj) {
    thisObj.Header=function Header() {
    this.SetFont('Arial','B',15);
    this.Cell(80);
    this.Cell(30,10,'Title',1,0,'C');
    this.Ln(20);
    }
    thisObj.Footer=function Footer() {
    this.SetY(-15);
    this.SetFont('Arial','I',8);
    this.Cell(0,10,'Page '+ this.PageNo()+ '/{nb}',0,0,'C');
    }
    }
    < /script >

    With this, you can call the function from VBScript, passing it your pdf object and it does the rest.

    Step 2 - Calling the function to change headers & footers
    Immediately after you've initialised your pdf object, call the function with something like this...

    redefineElement pdf


    PUTTING IT TOGETHER
    Here's a full page example that replicates Marco's original...


    < script language="javascript" runat="server" >
    function redefineElement(thisObj) {
    thisObj.Header=function Header() {
    this.SetFont('Arial','B',15);
    this.Cell(80);
    this.Cell(30,10,'Title',1,0,'C');
    this.Ln(20);
    }
    thisObj.Footer=function Footer() {
    this.SetY(-15);
    this.SetFont('Arial','I',8);
    this.Cell(0,10,'Page '+ this.PageNo()+ '/{nb}',0,0,'C');
    }
    }
    < /script >
    < SCRIPT LANGUAGE="VBScript" RUNAT="Server" >
    Set pdf=CreateJsObject("FPDF") ' Import class JScript in file VBScript
    redefineElement pdf

    pdf.CreatePDF() 'Call Class file
    pdf.SetPath("/scripts/fpdf/fpdf/") 'Set Path
    pdf.Open() 'Open PDF
    pdf.AddPage() ' add a page

    pdf.SetFont "Arial","",12 'Set Font
    for record=1 to 40
    pdf.Cell 0,10,"Printing line number "&record,0,1
    next
    pdf.output()
    < /script >
    ...and that should do it.

    NOTES
    There are a few issues...
    - The header & footer content code needs to be in Javascript (with brackets, etc.), so it codes slightly differently than the main body of the page
    - You could rewrite the javascript function to pass it header & footer code as variables, then eval it. This way, the javascript code could be centralised. I have a working demo of this method, but I wanted to keep this simple. I’m also working on passing it vbscript-formatted code and have it convert to Javascript in the background, but I’ll save that for another day
    - You'll need to remove the spaces out of the script tags, as they're not allowed here


    I hope this helps. It's not an elegant solution, but gets the job done. Please let me know if anything is unclear, as I've been working on this all day and might be a bit tired.

    ReplyDelete
  97. As an update to the my previous post, I have a much tidier version to implement headers and footers.

    It allows you to define your headers & footers fully in VBScript. It still calls a JS function to update the default Headers & Footers, but it's a standalone function that can be centralised.

    It's not completely tested, and there may well be a more efficient way of doing it, but it seems to work...

    Step 1 - Create file fpdf_addons.asp in your fpdf folder
    < script language="javascript" runat="server" >
    function setHeaderFooter(thisObj) {
    if(typeof vbHeader != "undefined") {
    thisObj.Header=function Header() { vbHeader(pdf); }
    }
    if(typeof vbFooter != "undefined") {
    thisObj.Footer=function Footer() { vbFooter(pdf); }
    }
    }
    < /script >


    Step 2 - Create a page with headers and footers in VBScript...


    < SCRIPT LANGUAGE="VBScript" RUNAT="Server" >
    Set pdf=CreateJsObject("FPDF") ' Import class JScript in file VBScript

    setHeaderFooter pdf ' setup H&F (function in fpdf_addons)

    pdf.CreatePDF() 'Call Class file
    pdf.SetPath("/scripts/fpdf/fpdf/") 'Set Path
    pdf.Open() 'Open PDF
    pdf.AddPage() ' add a page

    pdf.SetFont "Arial","",12 'Set Font
    for record=1 to 40
    pdf.Cell 0,10,"Printing line number "&record,0,1
    next
    pdf.output()

    Function vbHeader(thisObj)
    thisObj.SetFont "Arial","B",15
    thisObj.Cell 80
    thisObj.Cell 30,10,"Title",1,0,"C"
    thisObj.Ln 30
    End Function

    Function vbFooter(thisObj)
    thisObj.SetY -15
    thisObj.SetFont "Arial","I",8
    thisObj.Cell 0,10,"Page " & thisObj.PageNo() & "/{nb}",0,0,"C"
    End Function
    < /script >

    Instructions
    - Call the addons file in your pdf file. If used a lot, you could adjust the fpdf/includes/basics.asp file to automatically include it always (and put it in the includes folder)
    - After you've created the PDF, call the setHeaderFooter option, passing it your pdf object
    - This function will look for vbHeader and vbFooter functions. If it finds them it will pass the pdf object on
    - Put these functions on your pdf page and put in them anything that you want in the header/footer (in VBScript format). If you don't want a footer just don't put a function on the page
    - Remember in these functions to start all commands with "thisObj" rather than your pdf object name

    What's happening?
    - The VBScript is calling a Javascript function to redefine the header/footer functions
    - It rewrites these functions to call VBScript functions for the header/footer content
    - It may not be the most elegant solution, but it does mean that you can write your headers and footers in the same format as the rest of your page.

    ReplyDelete
    Replies
    1. Hi Simon, great job! Both versions are very helpful. Thanks a lot!

      Delete
  98. hey , if not mind ,i wanna know whether you guys used this barcode site

    ReplyDelete
  99. Hi, thank you for this tutorial! Hopefully more will follow still :)

    I had issues with charsets, and above tricks in comments did not help in my case. Then I tried changing the encoding of the actual asp file in a texteditor. My asp file was UTF-8 and when I changed the encoding to ANSI, special characters (which I needed) were shown correctly in PDF.

    Hopefully this helps someone in future.

    ReplyDelete
  100. Microsoft JScript runtime error '800a001c'

    Out of stack space

    /fpdf/includes/Basics.asp, line 190
    how to fix this error....
    length my string > 4000 char

    ReplyDelete
  101. None of this works and the file does not get written to the specified folder

    pdf.Close()
    fName = replace(arrApps(2,0), " ", "_") & "_" & AppType & "_Application.pdf"

    'response.write err.description
    filewrite = Server.MapPath("../../public/" & fName)

    response.write filewrite
    pdf.Output (filewrite)

    'Response.ContentType = "application/pdf"
    FPath = filewrite
    fn = fName

    Response.AddHeader "Content-Disposition","attachment; filename=" & fn

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing

    ReplyDelete
  102. I got issue about using FPDF on my classic asp page to generate pdf on the flight with custom true type font. I have tried also with "calligra" which exists in the font folder but no luck to get it works.

    I just simple create a pdf file with the following statement

    <%@language=vbscript%>
    <% Response.Buffer = true %>

    <%

    Set pdf=CreateJsObject("FPDF")
    pdf.CreatePDF "P","mm","A4"
    pdf.SetPath("fpdf/")
    pdf.Open()
    pdf.AddFont "AbadiMT", "", "__abalc.js"


    pdf.AddPage ()
    pdf.SetFont "AbadiMT","",35

    pdf.Write 10,"Enjoy @"& Now()
    pdf.Output
    %>

    When I run that asp page, I got

    Invalid or corrupted PDF file

    If I comment the line

    'pdf.AddFont "AbadiMT", "", "__abalc.js"
    'pdf.SetFont "AbadiMT","",35

    And add
    pdf.SetFont "Times","",35

    I got pdf content display with no issue.

    Any comments for my case?

    Best regards,

    Veasna

    ReplyDelete
  103. Hi, I'm new user here. How to start the above code? have no idea where to start from...

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.