Come integrare PDFarm nella tua applicazione

Torna all'indice
PDFarm "Web Service"

Per utilizzare PDFarm "Web Service" è necessario aver un hosting che supporti almeno un linguaggio di programmazione (es. PHP, ASP, .net, JSP, Perl e tutti gli altri) con cui sia possibile effettuare una chiamata HTTP remota al server PDFarm (www.pdfarm.net).
Effettuando una chiamata HTTP(S) POST al server PDFarm, in cui devono essere specificati i parametri chiave PDFarm e contenuto PHTML, si ottiene il relativo documento PDF.

Per ogni linguaggio di programmazione trovi di seguito il relativo tutorial per l'integrazione di PDFarm "Web Service" o "Server edition" nella tua applicazione:

Integrazione "Web Service" con linguaggio PHP

Integrazione "Web Service" con linguaggio .NET

Integrazione "Web Service" con linguaggio ASP.NET

Integrazione "Web Service" con linguaggio Java

Utilizzare PDFarm "Web service" con il linguaggio PHP:

Scarica la libreria PDFarmRequest.class.php (se hai installato le librerie curl come estensione PHP), altrimenti scarica le librerie
PDFarmRequest.socket.class.php (adatte anche dove non sono presenti le librerie curl).

N.B.Se hai acquistato la licenza PDFarm Web Service Light o Pro modifica la riga

define ('PDFARM_SERVICE_URL','http://www.pdfarm.net/services/generatorfree');

con

define ('PDFARM_SERVICE_URL','http://www.pdfarm.net/services/generator');

Le librerie permettono d'integrare la generazione PDF in modo molto semplice. Infatti è sufficiente specificare nella riga:

$phtmlRequest = new PDFarmRequest(“chiave-pdfarm-XXXXX-XXXXX”);

la propria chiave PDFarm ricevuta nella mail di conferma dell'acquisto (o di richiesta di una chiave dimostrativa) e specificare il PHTML di cui si vuole generare un PDF.
Ora non ti resta che avviare la generazione remota seguendo questo script:
<?php
//Se il PHP è configurato per il supporto alle librerie CURL
require_once(“PDFarmRequest.class.php”);
//Se il PHP è configurato SENZA il supporto alle librerie CURL
//require_once(“PDFarmRequest.socket.class.php”);

//Esempio di base PHTML
$phtml = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE phtml SYSTEM "PDFarm.dtd">
<phtml>
<body>
Hello World!
</body>
</phtml>';

//Istanza dell'oggetto PDFarmRequest, specificare la propria chiave PDFarm
$phtmlRequest = new PDFarmRequest(“chiave-pdfarm-XXXXX-XXXXX”);

//Assegnazione del contenuto PHTML
$phtmlRequest->setPHTML($phtml);

//Invio della richiesta di generazione del PDF
$ok = $phtmlRequest->sendRequest();

//Verifica e stampa eventuali errori
if(!$ok){
if($phtmlRequest->getError()=="")
echo "Si è verificato il seguente errore: PHTML Server could be down<br/>";
else
echo $phtmlRequest->getError();
}
else{
//Output del documento PDF direttamente al client per il download
$phtmlRequest->stream();
}

exit();
?>

Naturalmente è possibile dinamicizzare il PHTML come il seguente esempio:

<?php
//Esempio di base PHTML dinamico
//Definizione di un testo:
$documentTitle = “Intestazione del documento PDF”

//Definizione di una serie di colonne
$intestazioneTabella = {“col0”,“col1”,“col2”};

//Definizione di una serie di valori:
$valoriTabella = {“val0”,“val1”,“val2”};

$phtml = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE phtml SYSTEM "PDFarm.dtd">
<phtml>
<header height="50" align="center" valign="middle" border="1" backcolor="#FF9900">
<b color="#FFFFFF">'.
$documentTitle.
'</b>
</header>
<body>
</body>
</phtml>';

//Istanza dell'oggetto PDFarmRequest, specificare la propria chiave PDFarm
$phtmlRequest = new PDFarmRequest(“chiave-pdfarm-XXXXX-XXXXX”);

//Assegnazione del contenuto PHTML
$phtmlRequest->setPHTML($phtml);

//Invio della richiesta di generazione del PDF
$ok = $phtmlRequest->sendRequest();

//Verifica e stampa eventuali errori
if(!$ok){
if($phtmlRequest->getError()=="")
echo "Si è verificato il seguente errore: PHTML Server could be down<br/>";
else
echo $phtmlRequest->getError();
}
else{
//Output del documento PDF direttamente al client per il download
$phtmlRequest->stream();
}

exit();
?>

Utilizzare PDFarm "Web service" con il linguaggio .NET:

Apri Visual Web Developer (scaricabile gratuitamente da http://www.microsoft.com/express/download/).
Crea un nuovo sito web dal menu file: indica il nome (i.e. PDFarmTest) e seleziona il linguaggio (i.e. C#)

step1

Rinomina la pagina Default.aspx con un nome più adatto, per es: PDFarmRequest.aspx.
Verrà automaticamente rinominato alche il relativo file di codice C# diventando PDFarmRequest.aspx.cs.

step2

Clicca due volte sul file PDFarmRequest.aspx.cs in modo da aprirlo nella parte centrale dell'editor

step3

Il file contiene una parte di codice creata automaticamente dall'ambiente di sviluppo. Subito dopo la riga 9

step4

Inserire il codice seguente:

using System.IO;
using System.Net;
using System.Text;

Ottenendo quindi:

step5

Selezionare la parte di testo indicata:

step6

Sostituisci il testo selezionato con:

private static string CLIENT_KEY = "guest";
private static string PDFARM_SERVICE_URL = "http://www.pdfarm.net/services/generatorfree";

private string phtml = "";
private string error = "";
private byte[] pdf = null;

/*Setup PHTML code
*
* phtmlData -> String containing PHTML code (xml format)
*/
public void setPHTML(string phtmlData)
{
this.phtml = phtmlData;
}

/*Get PHTML code from given pat/to/filename
*
* $phtml -> String containing path/to/filename containing PHTML code (xml format)
*/
public void setPHTMLfile(string phtml_file)
{
//this.phtml = implode('', file (phtml_file));
}

/*Get last error generated by requested PDF
*
* Return a String containing last error occurred after a PDFarm Service request
*/
public string getError()
{
return this.error;
}

/*Return PDF content as PHP String
*
*Return a String containig binary PDF content
*/
public byte[] getPDF()
{
return this.pdf;
}

/*Resetting Object
*
* Useful method to reset object
*/
public void reset()
{
this.phtml = "";
this.pdf = null;
this.error = "";
}

/*Executing PDFarm Web Service request
*
* return true on success, false on error
*/
public void sendRequest()
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(PDFARM_SERVICE_URL);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";

//Post Data in right format
string str = "clientKey=" + CLIENT_KEY + "&phtmlData=" + HttpUtility.UrlEncode(this.phtml);


byte[] postBytes = Encoding.ASCII.GetBytes(str);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;


Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
BinaryReader responseStr = new BinaryReader(request.GetResponse().GetResponseStream());

BinaryWriter outStr = new BinaryWriter(new MemoryStream());


int buffer = 4096;
byte[] data = new byte[buffer];
int count = 0;
do
{
data = responseStr.ReadBytes(buffer);
outStr.Write(data, 0, data.Length);
count += data.Length;
}
while (data.Length > 0);
responseStr.Close();

outStr.BaseStream.Seek(0, 0);
this.pdf = new byte[count];
outStr.BaseStream.Read(this.pdf, 0, count);

outStr.Close();

}

/*Streaming PDF to the client (including correct header)
*
*Set headers and print out PDF binary data as inline file download (PDF plugin inside browser)
*/
public void streamToClient(HttpResponse responseStream)
{
int len = this.pdf.Length;
responseStream.ContentType = "x-application/pdf";
responseStream.AddHeader("Pragma", "no-cache");
responseStream.AddHeader("Content-Length:", len + "");
responseStream.BinaryWrite(this.pdf);
responseStream.End();
}

/*Streaming PDF to the client (including correct header)
*
*Set headers and print out PDF binary data as attachment file download (it shows "Save file as" dialog box)
*/
public void streamToClient(HttpResponse responseStream, string filename)
{
int len = this.pdf.Length;
responseStream.ContentType = "x-application/pdf";
responseStream.AddHeader("Pragma", "no-cache");
responseStream.AddHeader("Content-Length:", len + "");
responseStream.AddHeader("Content-Disposition", "attatchment; filename=\"" + filename + "\"");
responseStream.BinaryWrite(this.pdf);
responseStream.End();
}

Ottenendo quindi:

step7

Ora apri il file PDFarmRequest.aspx

step8

Aggiungi nella prima riga l'attributo

' ValidationRequest=”false” '

come indicato nella figura seguente:

step9

Aggiungi dalla seconda riga il codice seguente:

 <% 
if (Request.ServerVariables[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;)
{
_Default pdFarmRequest = new _Default();
pdFarmRequest.setPHTML(Request.Form.Get(&quot;phtmlData&quot;));
pdFarmRequest.sendRequest();
pdFarmRequest.streamToClient(Response, &quot;test.pdf&quot;);

}
%>

Ottenendo così il file come nell'immagine seguente:

step10

Infine sostituisci le righe che identificano il form presente di default nel file:

step11

Con il seguente codice:

	<form id="form1" method=post>
<div>
<textarea name="phtmlData" rows="10" cols=50><%
Response.Output.WriteLine(Server.HtmlEncode("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<!DOCTYPE phtml SYSTEM \"PDFarm.dtd\">\n" +
"<phtml>\n" +
"<body>Hello World!</body>\n" +
"</phtml>")
);
%>
</textarea>
<br />
<input type="submit" value="Generate!" />
</div>
</form>

Ottenendo quindi:

step12

Siamo pronti per provare PDFarm.
Cliccate con il tasto destro sul file PDFarmRequest.aspx nel pannello a destra e selezionate la voce visualizza nel browser:

step13

Il live generator è pronto!
Nel browser comparirà una textarea contenente del codice PHTML, cliccando sul tasto verrà generato il relativo PDF.

step14 Ora è possibile mantenere questsa pagina come generatore di tutti i vostri PDF.
E' sufficente che riceva tramite POST il codice PHTML da cui volete generare un PDF.

Utilizzare PDFarm "Web Service" con il linguaggio ASP.NET:

Il seguente codice ASP permette di utilizzare il PDFarm Web Service DEMO.

Se hai acquistato una licenza PDFarm Web Service Light o Pro modifica la riga:

Dim pdfarmUrl = "http://www.pdfarm.net/services/generatorfree"

con

Dim pdfarmUrl = "http://www.pdfarm.net/services/generator"

Il core del programma consiste in una chamata HTTP post con i due parametri clientKey (chiave utente per l'uso di PDFarm) e phtmlData (stringa XML strutturata in modo simile ad un HTML, per maggiorni informazioni vai alla relativa sezione della guida).
Sostituisci la chiave definita alla riga

Dim clientKey = "guest"

con la chiave PDFarm che hai ricevuto ottenendo:

Dim clientKey = "chiave-pdfarm-XXXX-XXXX"

In risposta alla richiesta si ottiene il documento PDF che, nel caso specifico, viene reinviato al client (eventualmente forzandone il download o la visualizzazione all'interno del browser attraverso il settaggio degli opportuni headers HTTP).

<%@LANGUAGE = "VBScript" aspcompat=true %><% ' Setup PDFarm server URL and client key Dim pdfarmUrl = "http://www.pdfarm.net/services/generatorfree"

' Setup clientKey
Dim clientKey = "guest"

' Setup PHTML string (static string for this simple example)

Dim phtmlData As StringBuilder = New StringBuilder

phtmlData.Append ("<?xml version=""1.0"" encoding=""UTF-8""?>")

phtmlData.Append ("<!DOCTYPE phtml SYSTEM ""PDFarm.dtd"">")
phtmlData.Append ("<phtml>")
phtmlData.Append ("<body>Hello World!</body>")
phtmlData.Append ("</phtml>")

' Setup POST params
Dim strPostData As StringBuilder = New StringBuilder
strPostData.Append ("clientKey=" & Server.URLEncode(clientKey) & "&phtmlData=" & Server.URLEncode (phtmlData.ToString ()))

' Instance XMLHTTP Object and sending POST request
Dim objxmlhttp = Server.CreateObject ("Microsoft.XMLHTTP")
objxmlhttp.Open ("POST", pdfarmUrl, false)

objxmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")
objxmlhttp.setRequestHeader ("content-length",strPostData.Length.ToString ())
objxmlhttp.send (strPostData.ToString ())

' If everything is OK streaming PDF document to the client
if CInt(objxmlhttp.Status) = 200 then

Response.ClearContent ()
Response.AppendHeader ("", objxmlhttp.responseBody.Length.ToString())
Response.ContentType = "application/pdf"

' Uncomment this line to force download (it do not use Adobe browser plugin)
' Response.AppendHeader ("Content-Disposition", "attatchment; filename=""" & filename &""" ")
Response.BinaryWrite (objxmlhttp.responseBody)

Response.Flush ()
Response.Close ()
else

Response.Write ("PDF generation error: " & objxmlhttp.responseText)

end if


' Cleaning request

objxmlhttp = Nothing

%>

<!-- NOT USED IN THIS EXAMPLE -->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled</title>
</head>
<body>
</body>
</html>


Utilizzare PDFarm "Web Service" con il linguaggio Java:

Il seguente codice Java permette di utilizzare il PDFarm Web Service DEMO.
Se hai acquistato una licenza PDFarm Web Service Light o Pro modifica la riga:

private static final String serviceURL = "http://www.pdfarm.net/services/generatorfree";

con

private static final String serviceURL = "http://www.pdfarm.net/services/generator";

Il core del programma consiste in una chamata HTTP post con i due parametri clientKey (chiave utente per l'uso di PDFarm) e phtmlData (stringa XML strutturata in modo simile ad un HTML, per maggiorni informazioni vai alla relativa sezione del tutorial).
Sostituisci la chiave definita alla riga

private static final String keycode = "guest";

con la chiave PDFarm che hai ricevuto ottenendo così:

private static final String keycode = "chiave-pdfarm-XXXX-XXXX";

In risposta alla richiesta si ottiene il documento PDF che puo' per esempio essere salvato in un file.

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class PDFarmTest {

private static final String keycode = "guest";
private static final String serviceURL = "http://www.pdfarm.net/services/generatorfree";

public static void main(String args[]){

/*
THIS IS A SAMPLE OF THE CODE THAT YOU NEED TO CREATE PDF, YOU MAY CUSTOMIZE
phtmlString GENERATION (I.E. WITH SAX, DOM OR YOUR OWN XML GENERATOR
AND CUSTOMIZE OUTPUT FILE CREATION
*/

String pdfOutFile = "sample.pdf";
String phtmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"<!DOCTYPE phtml SYSTEM \"PDfarm.dtd\">" +
"<phtml>" +
"<body>" +"Hello world!" +"</body>" +
"</phtml>";
System.out.println("Creating PDF File: "+pdfOutFile+"...");

/*
END OF YOUR CUSTOMIZED CODE, THE REST OF CODE IS THE SAME FOR EACH
APPLICATION
*/

PDFarmTest pdfarmreq = new PDFarmTest();
pdfarmreq.createPDFbyWS(phtmlString,pdfOutFile);

System.out.println("Done.");
}

/* USE THIS METHOD IN YOUR APPLICATION AS IS, JUST COMMENT OUT System.out(s)*/
public void createPDFbyWS(String phtmlString, String pdfFile){

HttpURLConnection conn = null;
try {
//Init URL Object
URL url = new URL( serviceURL );

//Open connection to PDFarm Server
conn = (HttpURLConnection)url.openConnection();
System.out.println("Connecting to PDFarm WebService...");

//Setup HTTP Params
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent", "PDFarm Java sample integration (this is optional)");
//This line is very important to send right data to WebServer
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

//Setup POST data (enconding XML with URLEncoder)
StringBuffer postparameter = new StringBuffer();
postparameter.append("clientKey="+URLEncoder.encode(keycode,"UTF-8"));
postparameter.append("&phtmlData="+
URLEncoder.encode(phtmlString,"UTF-8"));
OutputStreamWriter outStream = new OutputStreamWriter(
new BufferedOutputStream(conn.getOutputStream()));

//Sending data to PDFarm websevice

outStream.write( postparameter.toString() );
outStream.close();

System.out.println("Data sent.");

//Reading response
InputStream in = conn.getInputStream();
byte[] inLine = new byte[1024];

int count = 0;
int total = 0;
ByteArrayOutputStream result = new ByteArrayOutputStream(4096);

System.out.println("Reading data...");

do {
count = in.read(inLine, 0, 1024);
if(count>0){
result.write(inLine, 0, count);
total += count;
}

} while(count>0);

in.close();

//Writing file
System.out.println("Writing pdf file...");

//A simple test to check if response is a PDF document
if(result.toString("UTF-8").startsWith("%PDF")){

FileOutputStream fos = new FileOutputStream(
new File(pdfFile)
);

fos.write(result.toByteArray(), 0, total);
fos.close();
}else{
System.out.println("Error, received: "+result);
}

} catch (Exception e) {
e.printStackTrace();
}finally{
if(conn!=null)
conn.disconnect();
}
}
}
PDFarm "Server edition "

Per utilizzare PDFarm "Server edition" è necessario avere un computer con un sistema operativo (MS Windows®, Linux, Solaris®, etc...) che supporti e su cui sia installata Sun Java Platform Standard Edition versione 1.5.0 o successive (anche conosciuta come Sun Java SE 5).

Questo prodotto, a differenza di PDFarm "Web Service", è un pacchetto software che comprende l'intero generatore PDFarm da installare sul proprio server (o su un PC utilizzabile come gateway di generazione PDF).

Per attivare PDFarm "Server edition" è sufficiente seguire la semplice procedura guidata d'installazione eseguibile direttamente da linea di comando del proprio server.

Leggi i seguenti tutorial per conoscere come integrare PDFarm nella tua applicazione:

Integrazione "Server edition " con linguaggio PHP

Integrazione "Server edition" con linguaggio Java

Integrazione "Server edition" con linguaggio ASP

Integrazione "Server edition" con linguaggio .NET

Utilizzare PDFarm "Server edition " con il linguaggio PHP:

Scarica la libreria PDFarmServer.class.php.
N.B.Se hai acquistato attiva la licenza prima di utilizzare PDFarm, segui la guida che trovi qui


Ora non ti resta che avviare la generazione sul tuo server seguendo questo script:
<?php
//Se il PHP è configurato per il supporto alle librerie CURL require_once(“PDFarmServer.class.php”); //Esempio di base PHTML $phtml = '<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE phtml SYSTEM "PDFarm.dtd"> <phtml> <body> Hello World! </body> </phtml>'; $phtml = utf8_encode($phtml); //conversione della stringa nella codifica scelta nel XML $pdfarmServer = new PDFarmServer(); //Assegnazione del contenuto PHTML $pdfarmServer->setPHTML("esempio.phtml.xml",$phtml); //Invio della richiesta di generazione del PDF $result = $pdfarmServer->generate(); //Verifica e stampa eventuali errori if(!$result) { echo "Si è verificato il seguente errore: ".$pdfarmServer->getError()."<br/>"; }else{ //Output del documento PDF direttamente al client per il download file_put_contents("esempio.pdf",$result); } exit(); ?>

Utilizzare PDFarm "Server edition " con il linguaggio JAVA:

Il seguente codice Java permette di utilizzare PDFarm Server edition.
Il core del programma consiste nell'uso diretto delle API PDFarm per la creazione di un PDF secondo il layout definito da phtmlData (stringa XML strutturata in modo simile ad un HTML, per maggiorni informazioni vai alla relativa sezione del tutorial). L'esempio è pensato per creare un file PDF ma è possibile intercettare l'output e modificare il comportamento a proprio piacimento.

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import it.kiwiage.pdfarm.*;

public class PDFarmTest {

public static void main(String args[]){
/*
THIS IS A SAMPLE OF THE CODE THAT YOU NEED TO CREATE PDF, YOU MAY CUSTOMIZE
phtmlString GENERATION (I.E. WITH SAX, DOM OR YOUR OWN XML GENERATOR)
AND CUSTOMIZE OUTPUT FILE CREATION
*/
String pdfOutFile = "sample.pdf";
String phtmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"<!DOCTYPE phtml SYSTEM \"PDfarm.dtd\">" +
"<phtml>" +
"<body>" +
"Hello world!" +
"</body>" +
"</phtml>";

System.out.println("Creating PDF File: "+pdfOutFile+"...");
/*
END OF YOUR CUSTOMIZED CODE, THE REST OF CODE IS THE SAME FOR EACH
APPLICATION
*/

PDFarmTest pdfarmreq = new PDFarmTest();
pdfarmreq.createPDF(phtmlString,pdfOutFile);
System.out.println("Done.");
}

/* USE THIS METHOD IN YOUR APPLICATION AS IS, JUST COMMENT OUT System.out(s)*/
public void createPDF(String phtmlString, String pdfFile){

//Using trial PDFarm Server Edition lib
PDFarmDemo pdfarm = new PDFarmDemo( phtmlString );

//Using PDFarm Server Edition lib (it needs license activation)
//PDFarm pdfarm = new PDFarm( phtmlString );
try {
pdfarm.createPDF( new FileOutputStream(pdfFile) );
} catch (Exception e) {
e.printStackTrace();
}
}
}

Utilizzare PDFarm "Server edition " con il linguaggio ASP:

Il seguente codice ASP permette di utilizzare PDFarm Server Edition.
Il core del programma consiste nell'uso diretto del comando PDFarm per la creazione di un documento PDF secondo il layout definito dal file PHTML (per maggiorni informazioni visita la relativa sezione del tutorial). L'esempio presentato è pensato per creare automaticamente un file PDF a partire da un semplice file PHTML; questo codice può essere importato nella prorpia applicazione ASP e utilizzato ogni qual volta è necessario integrare PDFarm Server Edition.

<%
' Creazione del file phtml
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\inetpub\wwwroot\pdfarmexample\phtmls\example.phtml",true)

' Definizione del layout PHTML che genererà il PDF
fname.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
fname.WriteLine(<!DOCTYPE phtml SYSTEM \"PDFarm.dtd\">")
fname.WriteLine(<phtml>")fname.WriteLine(<body>")

fname.WriteLine(Hello World!")
fname.WriteLine(</body>")
fname.WriteLine(</phtml>")
fname.Close
set fname=nothing
set fs=nothing


' Generazione del file example.pdf dal file PHTML precedentemente creato lanciando PDFarm
Set oWSH= Server.CreateObject("WScript.Shell")
oWSH.Run "e;C:\Program Files\Sun\SDK\bin\java.exe -jar C:\path\to\PDFarm_3.1.XXX_XXXXX.jar -i C:\path\to\example.phtml -o C:\path\to\outdir\example.pdf"e;, 1, True
set oWSH = nothing


%>

L'ultima porzione di codice lancia il comando PDFarm in shell grazie a WSH; è possibile utilizzare altri oggetti altrettanto prestanti come ASPExec sostituendo le ultime tre righe di codice con:

  ' Generazione del file example.pdf dal file PHTML precedentemente creato lanciando PDFarm 
  ' con ASPExec
  Set Executor = Server.CreateObject("ASPExec.Execute")
  Executor.Application = "C:\Program Files\Sun\SDK\bin\java.exe"
  Executor.Parameters = "-jar C:\path\to\PDFarm_3.1.XXX_XXXXX.jar -i C:\path\to\example.phtml -o C:\path\to\outdir\example.pdf"
  Executor.ShowWindow = False
  Executor.ExecuteWinApp
  ' Il file rimane salvato sul server, è possibile redirezionare il client verso il file o 
  ' leggerlo e inviarne direttamente il contenuto
oppure, con ASPExec, diventa semplice redirezionare il documento PDF direttamente al client omettendo il paramentro -o C:\path\to\outdir\example.pdf e sfruttando direttamente l'output della generazione:
  ' Generazione del file example.pdf dal file PHTML precedentemente creato lanciando PDFarm 
  ' con ASPExec
  Set Executor = Server.CreateObject("ASPExec.Execute")
  Executor.Application = "C:\Program Files\Sun\SDK\bin\java.exe"
  Executor.Parameters = "-jar C:\path\to\PDFarm_3.1.XXX_XXXXX.jar -i C:\path\to\example.phtml -o C:\path\to\outdir\example.pdf"
  Executor.ShowWindow = False
  strResult = Executor.ExecuteWinApp
  Response.ClearContent
  
  ' Invio del PDF prodotto al client come allegato
  Response.AppendHeader ("content-length", strResult.Length.ToString())
  Response.ContentType = "application/pdf"
  Response.AppendHeader ("Content-Disposition", "attatchment; filename=example.pdf ")
  Response.BinaryWrite strResult

Un ulteriore oggetto ASP per utilizzare PDFarm Server Edition è DynuExec sostituendo le ultime tre righe del primo esempio con:
  Set oExec = Server.CreateObject("Dynu.Exec")
  Set pdfarmCmd = "C:\Program Files\Sun\SDK\bin\java.exe -jar C:\path\to\PDFarm_3.1.XXX_XXXXX.jar -i C:\path\to\example.phtml"
  
  ' Invio del PDF prodotto al client come allegato
  Response.AppendHeader ("content-length", strResult.Length.ToString())
  Response.ContentType = "application/pdf"
  Response.AppendHeader ("Content-Disposition", "attatchment; filename=example.pdf")
  Response.BinaryWrite(oExec.execute("pdfarmCmd"))
  Set oExec = nothing
N.B.: Fare particolare attenzione al settaggio sei permessi in ambienti NT prima di lanciare PDFarm. Il programma deve poter creare il file di output specificato con il paramentro '-o'

Utilizzare PDFarm "Server edition " con il linguaggio ASP.NET:

Il seguente codice ASP.NET permette di utilizzare PDFarm Server Edition.
Il core del programma consiste nell'uso diretto del comando PDFarm per la creazione di un documento PDF secondo il layout definito dal file PHTML (per maggiorni informazioni visita la relativa sezione del tutorial). L'esempio presentato è pensato per creare automaticamente un file PDF a partire da un semplice file PHTML; questo codice può essere importato nella prorpia applicazione classe ASP.NET e utilizzato ogni qual volta è necessario integrare PDFarm Server Edition.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if(Page.IsPostBack)
		{
			string exec = "C:\Program Files\Sun\SDK\bin\java.exe -jar C:\path\to\PDFarm_3.1.XXX_XXXXX.jar -i C:\path\to\example.phtml";
			

			// Create the ProcessInfo object
			System.Diagnostics.ProcessStartInfo pdfarmCmd = new System.Diagnostics.ProcessStartInfo("exec");
			pdfarmCmd.WindowStyle = ProcessWindowStyle.Hidden; 
			pdfarmCmd.UseShellExecute = true;
			pdfarmCmd.RedirectStandardOutput = true;
			pdfarmCmd.RedirectStandardInput = true;
			pdfarmCmd.RedirectStandardError = true;

			// Start the process
			System.Diagnostics.Process proc = System.Diagnostics.Process.Start(pdfarmCmd);
			
			// Attach the output for reading
			System.IO.StreamReader sOut = proc.StandardOutput;
			// Attach the in for writing
			System.IO.StreamWriter sIn = proc.StandardInput;
			
			//Wait process ends
			proc.WaitForExit();
			
			// Close the process
			proc.Close();

			// Read the sOut to a string.
			string pdfContent = sOut.ReadToEnd().Trim();

			// Close the io Streams;
			sOut.Close();

			// Stream result to client
			this.Response.BinaryWrite(pdfContent);

		}
	}
}