Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PDFCLOUD-2813 Add Attach to PDF samples #50

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Text;

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-attachment"))
{
request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
request.Headers.Accept.Add(new("application/json"));
var multipartContent = new MultipartFormDataContent();

var byteArray = File.ReadAllBytes("/path/to/file");
var byteAryContent = new ByteArrayContent(byteArray);
multipartContent.Add(byteAryContent, "file", "file_name");
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");

var byteArray2 = File.ReadAllBytes("/path/to/file");
var byteAryContent2 = new ByteArrayContent(byteArray2);
multipartContent.Add(byteAryContent2, "file_to_attach", "file_name");
byteAryContent2.Headers.TryAddWithoutValidation("Content-Type", "application/xml"); // Update content type

request.Content = multipartContent;
var response = await httpClient.SendAsync(request);

var apiResult = await response.Content.ReadAsStringAsync();

Console.WriteLine("API response received.");
Console.WriteLine(apiResult);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

public class PdfWithAddedAttachment {

// Specify the path to your file here, or as the first argument when running the program.
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";

// Specify the path to your file attachment here, or as the second argument when running the
// program.
private static final String DEFAULT_ATTACHMENT_PATH = "/path/to/file.xml";

// Specify your API key here, or in the environment variable PDFREST_API_KEY.
// You can also put the environment variable in a .env file.
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

public static void main(String[] args) {
File inputFile, attachmentFile;
if (args.length > 1) {
inputFile = new File(args[0]);
attachmentFile = new File(args[1]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
attachmentFile = new File(DEFAULT_ATTACHMENT_PATH);
}

final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
final RequestBody attachmentFileRequestBody =
RequestBody.create(attachmentFile, MediaType.parse("application/xml"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("file_to_attach", attachmentFile.getName(), attachmentFileRequestBody)
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url("https://api.pdfrest.com/pdf-with-added-attachment")
.post(requestBody)
.build();
try {
OkHttpClient client = new OkHttpClient().newBuilder().build();
Response response = client.newCall(request).execute();
System.out.println("Result code " + response.code());
if (response.body() != null) {
System.out.println(prettyJson(response.body().string()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private static String prettyJson(String json) {
// https://stackoverflow.com/a/9583835/11996393
return new JSONObject(json).toString(4);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* This request demonstrates how to apply a file watermark to a PDF. This kind of watermark uses another PDF (using either watermark_file or watermark_file_id as a form-data parameter) and applies it as a watermark to the primary input document (file or id).
* Horizontal and vertical offsets of the watermark are measured in PDF units. (1 inch = 72 PDF units)
*/
var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');

// Create a new form data instance and append the PDF file and parameters to it
var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('file_to_attach', fs.createReadStream('/path/to/file'));
data.append('output', 'pdfrest_pdf_with_added_attachment');

// define configuration options for axios request
var config = {
method: 'post',
maxBodyLength: Infinity, // set maximum length of the request body
url: 'https://api.pdfrest.com/pdf-with-added-attachment',
headers: {
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key
...data.getHeaders() // set headers for the request
},
data : data // set the data to be sent with the request
};

// send request and handle response or error
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});

// If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
require 'vendor/autoload.php'; // Require the autoload file to load Guzzle HTTP client.

use GuzzleHttp\Client; // Import the Guzzle HTTP client namespace.
use GuzzleHttp\Psr7\Request; // Import the PSR-7 Request class.
use GuzzleHttp\Psr7\Utils; // Import the PSR-7 Utils class for working with streams.

$client = new Client(); // Create a new instance of the Guzzle HTTP client.

$headers = [
'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Set the API key in the headers for authentication.
];

$options = [
'multipart' => [
[
'name' => 'file', // Specify the field name for the main PDF file.
'contents' => Utils::tryFopen('/path/to/file', 'r'), // Open the main PDF file specified by the '/path/to/file' for reading.
'filename' => '/path/to/file', // Set the filename for the main PDF file to be processed, in this case, '/path/to/file'.
'headers' => [
'Content-Type' => '<Content-type header>' // Set the Content-Type header for the main PDF file.
]
],
[
'name' => 'file_to_attach', // Specify the field name for the file attachment.
'contents' => Utils::tryFopen('/path/to/file', 'r'), // Open the file attachment specified by the '/path/to/file' for reading.
'filename' => '/path/to/file', // Set the filename for the file attachment to be added, in this case, '/path/to/file'.
'headers' => [
'Content-Type' => '<Content-type header>' // Set the Content-Type header for the file attachment.
]
],
[
'name' => 'output', // Specify the field name for the output option.
'contents' => 'pdfrest_pdf_with_added_attachment' // Set the value for the output option (in this case, 'pdfrest_pdf_with_added_attachment').
]
]
];

$request = new Request('POST', 'https://api.pdfrest.com/pdf-with-added-attachment', $headers); // Create a new HTTP POST request with the API endpoint and headers.

$res = $client->sendAsync($request, $options)->wait(); // Send the asynchronous request and wait for the response.

echo $res->getBody(); // Output the response body, which contains the processed PDF with the added attachment.
55 changes: 55 additions & 0 deletions Python/Endpoint Examples/JSON Payload/pdf-with-added-attachment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import requests
import json

with open('/path/to/pdf_file', 'rb') as f:
upload_pdf_data = f.read()

print("Uploading PDF file...")
upload_pdf_response = requests.post(url='https://api.pdfrest.com/upload',
data=upload_pdf_data,
headers={'Content-Type': 'application/octet-stream', 'content-filename': 'pdf_file.pdf', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"})

print("Upload PDF response status code: " + str(upload_pdf_response.status_code))


with open('/path/to/file_attachment', 'rb') as f:
upload_attachment_data = f.read()

print("Uploading file attachment...")
upload_attachment_response = requests.post(url='https://api.pdfrest.com/upload',
data=upload_attachment_data,
headers={'Content-Type': 'application/octet-stream', 'Content-Filename': 'data_file.xml', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"})

print("Upload data file response status code: " + str(upload_attachment_response.status_code))

if upload_pdf_response.ok and upload_attachment_response.ok:
upload_pdf_response_json = upload_pdf_response.json()
print(json.dumps(upload_pdf_response_json, indent = 2))

upload_attachment_response_json = upload_attachment_response.json()
print(json.dumps(upload_attachment_response_json, indent = 2))


uploaded_pdf_id = upload_pdf_response_json['files'][0]['id']
uploaded_attachment_id = upload_attachment_response_json['files'][0]['id']
added_attachment_data = { "id" : uploaded_pdf_id, "id_to_attach": uploaded_attachment_id }
print(json.dumps(added_attachment_data, indent = 2))


print("Processing file...")
added_attachment_response = requests.post(url='https://api.pdfrest.com/pdf-with-added-attachment',
data=json.dumps(added_attachment_data),
headers={'Content-Type': 'application/json', "API-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"})



print("Processing response status code: " + str(added_attachment_response.status_code))
if added_attachment_response.ok:
added_attachment_response_json = added_attachment_response.json()
print(json.dumps(added_attachment_response_json, indent = 2))

else:
print(added_attachment_response.text)
else:
print(upload_pdf_response.text)
print(upload_attachment_response.text)
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from requests_toolbelt import MultipartEncoder
import requests
import json

pdf_with_added_attachment_endpoint_url = 'https://api.pdfrest.com/pdf-with-added-attachment'

mp_encoder_pdfWithAddedAttachment = MultipartEncoder(
fields={
'file': ('file_name', open('/path/to/file', 'rb'), 'application/pdf'),
'file_to_attach': ('file_name', open('/path/to/file', 'rb'), 'application/xml'), # Update content type
'output' : 'example_out',
}
)

headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_pdfWithAddedAttachment.content_type,
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
}

print("Sending POST request to pdf-with-added-attachment endpoint...")
response = requests.post(pdf_with_added_attachment_endpoint_url, data=mp_encoder_pdfWithAddedAttachment, headers=headers)

print("Response status code: " + str(response.status_code))

if response.ok:
response_json = response.json()
print(json.dumps(response_json, indent = 2))
else:
print(response.text)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
curl -X POST "https://api.pdfrest.com/pdf-with-added-attachment" \
-H "Accept: application/json" \
-H "Content-Type: multipart/form-data" \
-H "Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \
-F "file=@/path/to/file" \
-F "file_to_attach=@/path/to/file" \
-F "output=example_out"