Skip to content

Instantly share code, notes, and snippets.

@illbzo1
Forked from janxious/DocRaptor.cs
Created August 14, 2012 17:09
Show Gist options
  • Save illbzo1/3350914 to your computer and use it in GitHub Desktop.
Save illbzo1/3350914 to your computer and use it in GitHub Desktop.
DocRaptor Examples Set 1 - Non-Ruby
/*
* Doc Raptor simple PHP example
* requires pecl_http extension
*
* This is a simple example of creating an excel file and saving it
* using Doc Raptor
*
* For other usage and examples, visit:
* http://docraptor.com/examples
*
* Doc Raptor http://docraptor.com
* Expected Behavior http://www.expectedbehavior.com
*/
<?php
$api_key = "YOUR_API_KEY_HERE";
$url = "https://docraptor.com/docs?user_credentials=$api_key";
$document_content = "<table><tr><td>Cell</td></tr></table>";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setPostFields(array('doc[document_content]' => $document_content,
'doc[document_type]' => 'xls',
'doc[name]' => 'my_doc.xls',
'doc[test]' => 'true'));
$request->send();
$file = fopen ("my_excel_doc.xls", "w");
fwrite($file, $request->getResponseBody());
fclose ($file);
?>
#This example will create a sample excel document with the authentication information as part of the POST data
curl -H "Content-Type:application/json" -d'{"user_credentials":"YOUR_API_KEY_HERE", "doc":{"name":"docraptor_sample.xls", "document_type":"xls", "test":"true", "document_content":"<table name=\"My First Sheet\"><tr><td>Cell 1</td><td>Cell 2</td></tr></table>"}}' http://docraptor.com/docs > docraptor_sample.xls
#This example will create a sample excel document with the authentication information as part of the URL
curl -H "Content-Type:application/json" -d'{"doc":{"name":"docraptor_sample.xls", "document_type":"xls", "test":"true", "document_content":"<table name=\"My First Sheet\"><tr><td>Cell 1</td><td>Cell 2</td></tr></table>"}}' http://docraptor.com/docs?user_credentials=YOUR_API_KEY_HERE > docraptor_sample.xls
#This example will create a sample pdf document with the authentication information as part of the POST data
curl -H "Content-Type:application/json" -d'{"user_credentials":"YOUR_API_KEY_HERE", "doc":{"name":"docraptor_sample.pdf", "document_type":"pdf", "test":"true", "document_content":"<html><body>Text in a PDF</body></html>"}}' http://docraptor.com/docs > docraptor_sample.pdf
#This example will create a sample pdf document with the authentication information as part of the URL
curl -H "Content-Type:application/json" -d'{"doc":{"name":"docraptor_sample.pdf", "document_type":"pdf", "test":"true", "document_content":"<html><body>Text in a PDF</body></html>"}}' http://docraptor.com/docs?user_credentials=YOUR_API_KEY_HERE > docraptor_sample.pdf
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
namespace DocRaptorConsoleExample {
class DocRaptor {
private const string PostFormat = "doc[{0}]={1}&doc[name]={2}&doc[document_type]={3}&doc[test]={4}";
private const string ApiKey = @"YOUR API KEY HERE";
private static string DocRaptorUrl = String.Format("https://docraptor.com/docs?user_credentials={0}", ApiKey);
public string DocumentContent { get; set; }
public string DocumentURL { get; set; }
public string Name { get; set; }
public bool Test { get; set; }
public bool CreateDocument(string type) {
if (string.IsNullOrEmpty(DocumentContent) && string.IsNullOrEmpty(DocumentURL)) {
Console.WriteLine("Please specify either DocumentContent or DocumentURL");
return false;
}
string postData = String.Format(PostFormat,
(string.IsNullOrEmpty(DocumentContent) ? "document_url" : "document_content"),
HttpUtility.UrlEncode(string.IsNullOrEmpty(DocumentContent) ? DocumentURL : DocumentContent),
HttpUtility.UrlEncode(Name),
HttpUtility.UrlEncode(type),
HttpUtility.UrlEncode(Test.ToString().ToLower()));
var byteArray = Encoding.UTF8.GetBytes(postData);
var request = (HttpWebRequest)WebRequest.Create(DocRaptorUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); }
try {
var response = request.GetResponse();
using (var dataStream = response.GetResponseStream()) {
using (Stream file = File.OpenWrite(Name)) { CopyStream(dataStream, file); }
}
Console.WriteLine("File Saved");
return true;
} catch (WebException e) {
if (e.Status == WebExceptionStatus.ProtocolError) {
var response = (HttpWebResponse)e.Response;
string errorResponse;
using (var dataStream = response.GetResponseStream()) {
using (var reader = new StreamReader(dataStream)) { errorResponse = reader.ReadToEnd(); }
}
Console.WriteLine(errorResponse);
Console.WriteLine(string.Format("{0} - {1}", response.StatusCode, response.StatusDescription));
} else {
Console.WriteLine(e.Message);
}
}
return false;
}
public static void CopyStream(Stream input, Stream output) {
var buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); }
}
public bool CreatePDF() {
return this.CreateDocument("pdf");
}
public bool CreateXLS() {
return this.CreateDocument("xls");
}
static void Main(string[] args) {
/*** PDF Example ***/
DocRaptor doc_raptor = new DocRaptor() {
DocumentContent = @"<html><body>This is a DocRaptor example!</body></html>",
Name = "csharp_sample.pdf",
Test = true
};
doc_raptor.CreatePDF();
/*** Excel Example ***/
/*DocRaptor doc_raptor = new DocRaptor() {
DocumentContent = @"<table name="Test Sheet"><tr><td>I am a cell!</td></tr></table>",
Name = "csharp_sample.xls",
Test = true
};
doc_raptor.CreateXLS(); */
}
}
}
// this function is based on code found:
// http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
// to easily make a form and POST it
var download = function(url, data, method){
//url and data options required
if( url && data ){
jQuery('<form style="display: none" id="dr_submission" action="' + url
+ '" method="' + (method||'post') + '">'
+ '</form>').appendTo('body');
//credentials
jQuery('form#dr_submission').append('<textarea name="user_credentials"></textarea>');
jQuery('form#dr_submission textarea[name=user_credentials]').val(data.user_credentials);
//doc values
for(var key in data.doc) {
jQuery('form#dr_submission').append('<textarea name="doc['+key+']"></textarea>');
jQuery('form#dr_submission textarea[name="doc['+key+']"]').val(data.doc[key]);
}
//submit the form
if(confirm("press ok")) {jQuery('form#dr_submission').submit().remove(); }
};
};
// setup the string represeting the html we want to submit
var content = '<table name="foo"><tr><td>word up</td></tr></table><textarea>Foo&nbsp;&nbsp;&trade;&nbsp;&nbsp;Bar</textarea><p>What happens to +\'s?</p>';
var data = {
doc: {
test: true,
document_type: 'pdf',
name: 'adoc',
document_content: content,
strict: 'none'
},
user_credentials: "YOUR_API_KEY"
};
// this drops a form on the page and submits, which will result in a download dialog popping up
download("http://docraptor.com/docs.xls", data);
// this function is based on code found:
// http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
// to easily make a form and POST it
var download = function(url, data, method){
//url and data options required
if(url && data){
//data can be string of parameters or array/object
data = jQuery.param(data);
// make the entire request against a url instead of as form params
url += '?' + data
//send request
jQuery('<form style="display: none" action="' + url
+ '" method="' + (method||'post') + '">'
+ '</form>').appendTo('body').submit().remove();
}
};
// setup the string represeting the html we want to submit
var content = '<table name="foo"><tr><td>word up</td></tr></table><textarea>Foo&nbsp;&nbsp;&trade;&nbsp;&nbsp;Bar</textarea>';
var data = {
doc: {
test: true,
document_type: 'pdf',
name: 'adoc',
document_content: content,
strict: 'none'
},
user_credentials: 'YOUR_API_KEY'
};
// this drops a form on the page and submits, which will result in a download dialog popping up
download("http://docraptor.com/docs", data);
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Windows;
using Microsoft.Win32;
namespace DocRaptorExample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const string PostFormat = "doc[document_content]={0}&doc[name]={1}&doc[document_type]={2}&doc[test]={3}";
private const string ApiKey = "YOUR_API_KEY_HERE";
private static string DocRaptorUrl = String.Format("https://docraptor.com/docs?user_credentials={0}", ApiKey);
public MainWindow()
{
InitializeComponent();
SampleExcelContentClick(null, null);
}
private void SampleExcelContentClick(object sender, RoutedEventArgs e)
{
_DocumentContent.Text =
"<table name='My First Sheet'>\n <tr>\n <td>Cell 1</td>\n <td>Cell 2</td>\n </tr>\n</table>";
}
private void SamplePDFContentClick(object sender, RoutedEventArgs e)
{ _DocumentContent.Text = "<html>\n <body>\n Some Text in a PDF\n </body>\n</html>"; }
private void CreateExcelClick(object sender, RoutedEventArgs e)
{ CreateDocument(_DocumentContent.Text, "xls", true); }
private void CreatePDFClick(object sender, RoutedEventArgs e)
{ CreateDocument(_DocumentContent.Text, "pdf", true); }
public static void CreateDocument(string documentContent, string type, bool test)
{
var sfd = new SaveFileDialog();
if (sfd.ShowDialog() != true) { return; }
var postData = String.Format(PostFormat, HttpUtility.UrlEncode(documentContent),
HttpUtility.UrlEncode(sfd.SafeFileName),
HttpUtility.UrlEncode(type),
HttpUtility.UrlEncode(test.ToString().ToLower()));
var byteArray = Encoding.UTF8.GetBytes(postData);
var request = (HttpWebRequest)WebRequest.Create(DocRaptorUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream())
{ dataStream.Write(byteArray, 0, byteArray.Length); }
try
{
var response = request.GetResponse();
using (var dataStream = response.GetResponseStream())
{
using (Stream file = File.OpenWrite(sfd.FileName))
{ CopyStream(dataStream, file); }
}
MessageBox.Show("File Saved", "Success");
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
var response = (HttpWebResponse)e.Response;
string errorResponse;
using (var dataStream = response.GetResponseStream())
{
using (var reader = new StreamReader(dataStream))
{ errorResponse = reader.ReadToEnd(); }
}
MessageBox.Show(errorResponse, String.Format("{0} - {1}", response.StatusCode, response.StatusDescription));
}
else
{
MessageBox.Show(e.Message, "Error");
}
}
}
public static void CopyStream(Stream input, Stream output)
{
var buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{ output.Write(buffer, 0, len); }
}
private void OpenLinkClick(object sender, RoutedEventArgs e)
{ System.Diagnostics.Process.Start(((System.Windows.Documents.Hyperlink)sender).NavigateUri.ToString()); }
}
}
// this function is based on code found:
// http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/
// to easily make a form and POST it
var download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : $H(data).toQueryString();
//split params into form inputs
var inputs = '';
data.split('&').each(function(s){
var pair = s.split('=');
var name = pair.shift();
var value = pair.join("=");
inputs+='<textarea name="'+ name +'">'+ value +'</textarea>';
});
//send request
$$('body')[0].insert('<form id="DocRaptor-example" style="display: none" action="' + url
+ '" method="' + (method||'post') + '">'
+ inputs +
'</form>');
$('DocRaptor-example').submit();
$('DocRaptor-example').remove();
};
};
// setup the string represeting the table we want to submit
var content = '<table name="foo"><tr><td>word up</td></tr></table>';
// this drops a form on the page and submits, which will result in a download dialog popping up
download("http://docraptor.com/docs.xls",
"doc[document_content]=" + content +
"&doc[name]=adoc&user_credentials=<YOUR_API_KEY_HERE>");
import time
from docraptor import DocRaptor
docraptor = DocRaptor()
with open("test_document.pdf", "wb") as f:
f.write(docraptor.create({
'document_content': '<h1>python-docraptor</h1><p>Basic Test</p>',
'test': True
}).content)
#This simple Curl example will create a sample test PDF with the authentication information as part of the POST data. All you have to do is copy this code, plug in your API key, and paste it into a command line.
curl -H "Content-Type:application/json" -d'{"user_credentials":"YOUR_API_KEY_HERE", "doc":{"name":"docraptor_sample.pdf", "document_type":"pdf", "test":"true", "document_url":"http://www.docraptor.com"}}' http://docraptor.com/docs > docraptor_sample.pdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment