# PDFShift — Full Content
> Complete text of pdfshift.io, generated from the site's source Markdown. PDFShift is a developer-first API that converts HTML, URLs, and raw markup into pixel-perfect PDFs, screenshots, and Open Graph images.
Source: https://pdfshift.io — see also https://pdfshift.io/llms.txt for a curated index.
Pricing details: https://pdfshift.io/pricing.md
Documents: 635. Each is delimited by a rule and prefixed with its canonical URL.
---
# PDFShift FAQ
Source: https://pdfshift.io/faq
# PDFShift FAQ
## Trying PDFShift
**Can I try PDFShift for free?**
Yes. Follow this link to create an account and get 50 credits per month for free. You won’t be charged, and you don’t need to enter credit card details to get started. Once you’ve created your account and logged in, access our API to convert up to 50 documents for free.
**What can I do with PDFShift?**
This covers a broad range of tasks involving converting documents to PDF, grabbing screenshots, and generating Open Graph images. You can use PDFShift for invoice generation for your customers, export images from a graphics editor, and much more.
**Can I try PDFShift without creating an account?**
Yes. Head to our Playground to see how you can customize your document conversion output with code samples — whether it’s an image or a PDF.
## Using PDFShift
**What types of content can I convert with PDFShift?**
For starters, PDFShift supports HTML documents of any kind. That means web pages from your site or anywhere else on the internet, Canvas objects like image editing output, and more. You can also work with non-HTML libraries like React, VueJS, ChartJS, D3.js, and many more.
**How do you ensure high-quality conversions and service uptime?**
PDFShift runs on Chromium, which enables perfect rendering every time. As for uptime, our server infrastructure is structured to perform at its best even under high stress, and has several redundancies built in. As a result, our customers experience 99.9% uptime. You can track our service availability on [our Status page](https://status.pdfshift.io/).
**What sort of support can I expect as a PDFShift customer?**
If you face any problems running PDFShift, you can consult our extensive and simple documentation, flip through our guides for working with various programming languages, or contact us directly via this form.
We respond to Business plan users’ requests within hours of receiving a support ticket; for all our other paid plans, we respond within 12 hours. We respond to Free plan users’ tickets within 2 days.
You can track our uptime on [our Status page](https://status.pdfshift.io/).
**What if I have custom requirements?**
Contact us via our form or email us, and we’ll do our best to accommodate your needs with the most suitable implementation.
**What about the privacy of my data?**
We take privacy seriously. We do not store requests or generated documents. As such, it's impossible for us to view the content you convert using PDFShift — so you can rest assured that your documents are entirely private.
**Is PDFShift GDPR compliant?**
Yes. You can read our [Data Processing Agreement](https://pdfshift.io/legal/dpa) along with our [Privacy Policy](https://pdfshift.io/legal/privacy) for more details.
## Pricing and payments
**How do credits work, and how are conversions counted?**
PDFShift’s free and paid plans count usage on the basis of credits; each credit is good for one conversion of up to 5MB. That means if you convert one document that generates, say, a 200KB or 2MB PDF, it’ll be count as a single credit against your quota.
If you convert a document that exceeds 5MB, you’ll use additional credits towards the same document. For example, if a single document conversion works out to 9MB, that’ll count as 2 credits against your quota. Similarly, a single 14MB document will count as 3 credits.
**How much does PDFShift typically cost?**
The average PDFShift customer uses 1,300 credits a month. The plan that matches this usage pattern is the Boost plan at $24 a month. This plan includes 2,500 monthly credits, as well as a low overage cost of just $0.03 per conversion.
PDFShift can meet your needs with higher volume plans. Contact us to ask for a dedicated plan.
**Which payment methods are supported?**
We accept payments through Visa, Mastercard, American Express, Discover, JCB, and Diner's Club cards via Stripe.
**Do you offer annual plans?**
Yes, indeed. If you sign up for an annual plan, you’ll only pay for 10 months.
Head to our Pricing page to learn more.
**What happens if I exceed my API request volume?**
We will automatically notify you at 50%, 80% and 100% of your credit usage. You can also enable our overage system to not be blocked after hitting 100% of your quota.
**How does your API request overage system work?**
Every plan has an ‘overage’ cost associated with it. When you go over the plan’s limit (say, 1,000 credits in a single month), all the credits you use above that limit will be multiplied by the overage cost, and you’ll be billed for that usage specifically in a separate invoice when your subscription comes up for renewal.
For example, let’s say you’re on the $24/month Boost plan which includes 2,500 monthly credits. If you use 2,700 credits in a given month, you’ll pay:
- $24 for the 2,500 credits
- 200 credits x $0.03 for conversions above your credit limit, which works out to $6
That comes to a total of $30 for that month.
## Integrating and implementing PDFShift
**Do I need to make a page publicly available to use PDFShift?**
No, you don't need to put the page you want to convert publicly on the web. You can simply send the HTML to PDFShift instead by following this guide.
## I forgot to set the `sandbox` parameter while testing and used up all my credits. What now?
No problem! [Contact us](/contact) and we’ll top up your account with more credits during your first month for free.
**What is the timeout for conversions?**
We wait up to 30 seconds by default for free plans, and 100 seconds for paid plans. If your document needs longer timeouts and you’re on one of PDFShift’s premium plans, contact us and we'll adjust it accordingly for your account.
**What happens when requests time out?**
When a conversion takes too long, PDFShift returns a JSON response along with a 408 status message to inform you that your request has timed out.
**How many parallel conversions can I run? Is it different for each plan?**
You can make up to 50 parallel conversions at the same time. This limit applies to all plans by default — but if you need more parallel conversions, contact us for a custom solution.
**Do I have to pass a "webhook" parameter when using parallel conversion?**
Yes. When you carry out parallel conversions, PDFShift queues up each request to be processed independently. For this reason, your POST request is treated almost instantly with a 202 status code (’Accepted’). You will then receive a POST response at your Webhook URL for **each** source that is converted.
**I use Amazon S3 storage for my converted documents — how is my data privacy maintained?**
When you pass the "filename" parameter while processing HTML content, we store your resulting documents at our Amazon's S3 storage. In this case, the PDF's content is subject to Amazon's privacy policy.
For increased privacy, PDFShift supports sending your documents straight to your own S3 storage. Find our documentation here.
**What if I have other questions?**
Feel free to [reach out to us via email](/contact), and we'll be happy to answer to all your questions.
---
# Fast, Easy Website and HTML to PDF Converter via API | PDFShift
Source: https://pdfshift.io/
Description: An API to convert HTML/CSS documents to PDF. Fast, reliable, and pixel-perfect conversions for developers. Start with 50 free credits per month.
# PDFShift - HTML to PDF Conversion API
## From HTML to pixel-perfect PDFs in seconds
Our always-up-to-date API for developers automates your document conversion tasks - effortlessly.
[Register for free](/register)
## Key Statistics
- **300+ Million** Conversions made
- **15,000+** Developers
- **1.5s** Average conversion time
- **99.99%** Uptime
## Trusted by Leading Companies
PDFShift is used by thousands of companies worldwide for their PDF generation needs.
## Powerful Features for High-Fidelity Documents
### Full CSS Support
Our powerful engine supports all the latest CSS features, including custom web fonts, flexbox, grid layouts, and responsive design.
### JavaScript Execution
Execute JavaScript before converting your pages to capture dynamic content and single-page applications.
### Headers & Footers
Add custom headers and footers with page numbers, dates, and dynamic content.
### Watermarks
Protect your documents with text or image watermarks, positioned precisely where you need them.
### Password Protection
Secure your PDFs with password protection and encryption.
### Screenshot Capture
Generate high-quality screenshots of web pages in various formats (PNG, JPEG, WebP).
## API-First Design
Built for developers, by developers. Our RESTful API integrates seamlessly with any programming language or framework:
- Node.js
- Python
- PHP
- Ruby
- Go
- C#
## Features
### Perfect Rendering
Powered by Chromium for pixel-perfect rendering every time.
### Custom Page Sizes
Support for standard sizes (A4, Letter) and custom dimensions.
### Landscape & Portrait
Convert in any orientation.
### Webhooks
Get notified when conversions complete via webhooks.
### Cloud Storage Integration
Save directly to Amazon S3 or get a temporary URL.
### Custom HTTP Headers
Send custom headers for authenticated pages.
### CSS & JavaScript Injection
Load additional CSS or JavaScript from strings or URLs.
### Page Selection
Export specific pages or page ranges from your document.
### Full-Height Documents
Generate PDFs with full page height without pagination.
### Timeout Control
Set custom timeouts for complex page rendering.
## Pricing
Flexible plans to suit your needs:
- **Free**: 50 credits/month, no credit card required
- **Starter**: Ideal for small projects
- **Business**: For growing companies
- **Enterprise**: Custom solutions with SLA
[View detailed pricing](/pricing)
## Resources
- [API Documentation](https://docs.pdfshift.io)
- [API Status](https://status.pdfshift.io)
- [Guides & Tutorials](/guides)
- [FAQ](/faq)
## Start Converting Today
Get started in minutes with our comprehensive documentation and code examples. No credit card required for the free tier.
[Create your free account](/register)
---
**Support**: Available for all plans with response times based on your subscription level.
**Privacy**: GDPR compliant. We don't store your documents or requests.
**Reliability**: 99.9% uptime with multiple redundancies.
---
# PDFShift Pricing
Source: https://pdfshift.io/pricing
# PDFShift Pricing
Start for free and scale from a handful of documents to millions of conversions with simple, credit-based plans. No credit card required to get started.
## Plans
| Plan | Price | Per year | Credits / mo | Overage (per credit) |
| ---------- | --------- | ---------- | ------------ | -------------------- |
| Free | $0/mo | — | 50 | — |
| Starter | $9/mo | $90/yr | 500 | $0.04 |
| Boost | $24/mo | $240/yr | 2,500 | $0.03 |
| Growth | $39/mo | $390/yr | 5,000 | $0.025 |
| Business | $99/mo | $990/yr | 25,000 | $0.02 |
| Shift 50k | $149/mo | $1,490/yr | 50,000 | $0.015 |
| Shift 100k | $249/mo | $2,490/yr | 100,000 | $0.01 |
| Shift 250k | $499/mo | $4,990/yr | 250,000 | $0.005 |
| Shift 500k | $799/mo | $7,990/yr | 500,000 | $0.003 |
| Shift 1M | $999/mo | $9,990/yr | 1,000,000 | $0.001 |
| Custom | Custom | Custom | 1,000,000+ | Custom |
Annual billing is 10 months for the price of 12 (two months free). The overage rate applies only to credits used beyond your included monthly volume.
## What is a credit?
One credit is consumed per document, counted per 5 MB of generated data. A conversion that produces a 14 MB PDF counts as 3 credits. Unused credits do not roll over from month to month.
## Cost Examples
To illustrate costs at common volumes, here are the recommended plans and their effective per-document rate:
- **500 documents/mo**: Starter at $9/mo — effective rate of $0.018 per document.
- **5,000 documents/mo**: Growth at $39/mo — effective rate of $0.0078 per document.
- **25,000 documents/mo**: Business at $99/mo — effective rate of $0.00396 per document.
- **50,000 documents/mo**: Shift 50k at $149/mo — effective rate of $0.00298 per document.
- **500,000 documents/mo**: Shift 500k at $799/mo — effective rate of $0.0016 per document.
- **1,000,000 documents/mo**: Shift 1M at $999/mo — effective rate of $0.001 per document.
## Feature Highlights
- **Free**: 50 credits / mo, CSS & JavaScript injection, advanced header & footer, encryption & watermark, max file size 15 MB, 30 second timeout.
- **Paid (Starter and above)**: Everything in Free, plus no file size limit, timeout up to 15 minutes, AWS S3 delivery, and parallel & asynchronous responses.
All plans include: RESTful API, CSS & JavaScript injection, advanced headers & footers, PDF encryption and watermarking, and access to our full guides and documentation.
## Enterprise / High Volume
We easily support more than 1 million conversions per month. For teams with high-volume or custom needs, reach out and we'll put together a tailored quote.
[Contact us for a custom quote](/contact).
## Get Started
Start converting HTML to PDF for free — 50 credits every month, no credit card required.
[Register for free](/register)
---
# Accessing secured pages — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/accessing-secured-pages
Description: Learn how to access secured pages using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, highlighting how you can access page protected by basic authentication to convert them to PDF using PDFShift's API.
In this guide, we'll show you how to access secured page (protected by basic authentication) using C# and the HttpClient library to convert them to PDF using PDFShift's API.
When you're converting a document, you might want to access a secured page (protected by basic authentication) to convert it to PDF. This can be done by setting the `auth` parameter to the request.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// You can set a basic authentication by passing the "auth" property which contains a username and password
auth = new
{
username = "user",
password = "password"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to protect your documents from any visitors while allowing PDFShift to access the page and convert it to PDF.
---
# Adding a custom header or footer — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/adding-a-custom-header-or-footer
Description: Learn how to add custom headers and footers to your PDFs using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to customize PDF appearance with headers and footers.
In this guide, we'll show you how to add custom headers and footers to your PDFs using C# and the HttpClient library.
When generating PDFs, you might want to add custom headers and footers to your documents for branding or informational purposes.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Add custom header and footer
header = new
{
content = "
Header Content
",
height = "20mm"
},
footer = new
{
content = "Footer Content
",
height = "20mm"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to add consistent branding elements to all your generated PDF documents.
---
# Adding a text watermark — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/adding-a-text-watermark
Description: Learn how to add text watermarks to your PDFs using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to apply text watermarks to protect your documents.
In this guide, we'll show you how to add text watermarks to your PDFs using C# and the HttpClient library.
When generating PDFs, you might want to add text watermarks to your documents for protection or branding purposes.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Add text watermark
watermark = new
{
text = "CONFIDENTIAL",
opacity = 0.3,
size = "20px",
color = "#000000"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to add textual protection to your documents with customizable text.
---
# Adding an image watermark — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/adding-an-image-watermark
Description: Learn how to add image watermarks to your PDFs using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to apply image watermarks to protect your documents.
In this guide, we'll show you how to add image watermarks to your PDFs using C# and the HttpClient library.
When generating PDFs, you might want to add image watermarks to your documents for protection or branding purposes.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Add image watermark
watermark = new
{
image = "https://example.com/watermark.png",
opacity = 0.5,
position = "center"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to add visual protection to your documents with custom images.
---
# Avoid conversion on error — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/avoid-conversion-on-error
Description: Learn how to avoid conversion on error using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to handle conversion errors gracefully.
In this guide, we'll show you how to avoid conversion on error using C# and the HttpClient library.
When converting documents to PDF, you might want to prevent conversion if certain errors occur to avoid generating invalid PDFs.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Prevent conversion on error
continue_on_error = false
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to fail fast when conversion issues occur.
---
# Convert HTML to PDF from a URL — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/convert-html-to-pdf-from-a-url
Description: Learn how to convert HTML from a URL to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to convert online HTML content to PDF.
In this guide, we'll show you how to convert HTML from a URL to PDF using C# and the HttpClient library.
Converting HTML from a URL to PDF is a common requirement when you want to generate PDFs from existing web content.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to easily convert any webpage to a PDF document.
---
# Convert HTML to PDF from raw HTML — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/convert-html-to-pdf-from-raw-html
Description: Learn how to convert raw HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to convert HTML content directly to PDF.
In this guide, we'll show you how to convert raw HTML to PDF using C# and the HttpClient library.
Converting raw HTML content to PDF is useful when you have HTML content that isn't hosted on a web server.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "Hello World
"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to convert HTML content directly to PDF without needing a URL.
---
# Define a time limit — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/define-a-time-limit
Description: Learn how to define a time limit for PDF conversions using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to set timeouts to prevent long-running conversions.
In this guide, we'll show you how to define a time limit for PDF conversions using C# and the HttpClient library.
When converting documents to PDF, you might want to set a timeout to prevent long-running conversions from blocking your application.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Set a timeout in seconds
timeout = 30
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to control how long a conversion can take before timing out.
---
# Exporting only a specific set of pages — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/exporting-only-a-specific-set-of-pages
Description: Learn how to export only specific pages from a document when converting to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to select specific pages for export.
In this guide, we'll show you how to export only specific pages from a document when converting to PDF using C# and the HttpClient library.
When converting documents, you might want to export only a specific range of pages rather than the entire document.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Export only pages 1-3
pages = "1-3"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to selectively export pages from multi-page documents.
---
# Generate a document with full height — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/generate-a-document-with-full-height
Description: Learn how to generate a document with full height using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to create full-height PDFs.
In this guide, we'll show you how to generate a document with full height using C# and the HttpClient library.
When converting documents to PDF, you might want to ensure the entire document height is preserved.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Generate document with full height
full_height = true
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This ensures the entire document content is included in the PDF.
---
# Loading CSS from a string — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/loading-css-from-a-string
Description: Learn how to load CSS from a string when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to apply inline CSS styling.
In this guide, we'll show you how to load CSS from a string when converting HTML to PDF using C# and the HttpClient library.
When converting HTML to PDF, you might want to apply CSS styling using inline CSS rather than external stylesheets.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load CSS from a string
css = "body { font-family: Arial; } h1 { color: blue; }"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to apply custom styling directly to your PDFs.
---
# Loading CSS from a URL — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/loading-css-from-a-url
Description: Learn how to load CSS from a URL when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to reference external CSS files.
In this guide, we'll show you how to load CSS from a URL when converting HTML to PDF using C# and the HttpClient library.
When converting HTML to PDF, you might want to reference external CSS files to maintain consistent styling.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load CSS from a URL
css = "https://example.com/styles.css"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to apply external stylesheets to your PDFs.
---
# Loading JavaScript from a string — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/loading-javascript-from-a-string
Description: Learn how to load JavaScript from a string when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to include inline JavaScript.
In this guide, we'll show you how to load JavaScript from a string when converting HTML to PDF using C# and the HttpClient library.
When converting HTML to PDF, you might want to include JavaScript functionality using inline code.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load JavaScript from a string
javascript = "document.body.style.backgroundColor = 'red';"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This enables dynamic behavior in your PDFs.
---
# Loading JavaScript from a URL — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/loading-javascript-from-a-url
Description: Learn how to load JavaScript from a URL when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to reference external JavaScript files.
In this guide, we'll show you how to load JavaScript from a URL when converting HTML to PDF using C# and the HttpClient library.
When converting HTML to PDF, you might want to reference external JavaScript files to include dynamic functionality.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load JavaScript from a URL
javascript = "https://example.com/script.js"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to include external JavaScript libraries in your PDFs.
---
# Protecting the generated PDF — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/protecting-the-generated-pdf
Description: Learn how to protect generated PDFs with passwords using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to secure your PDF documents.
In this guide, we'll show you how to protect generated PDFs with passwords using C# and the HttpClient library.
When generating PDFs, you might want to add password protection to restrict access.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Protect the PDF with a password
protection = new
{
user_password = "user123",
owner_password = "owner123"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to secure your PDF documents with passwords.
---
# Receive a webhook event — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/receive-a-webhook-event
Description: Learn how to receive webhook events when PDF conversion is complete using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to handle asynchronous conversion notifications.
In this guide, we'll show you how to receive webhook events when PDF conversion is complete using C# and the HttpClient library.
When converting documents asynchronously, you might want to be notified when the conversion is complete via a webhook.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Set up webhook notification
webhook = new
{
url = "https://your-server.com/webhook",
secret = "your-secret-key"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to be notified when conversions are complete without polling.
---
# Save your PDF online and get back a URL — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/save-your-pdf-online-and-get-back-a-url
Description: Learn how to save your PDF online and get back a URL using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to store PDFs in cloud storage and retrieve URLs.
In this guide, we'll show you how to save your PDF online and get back a URL using C# and the HttpClient library.
When generating PDFs, you might want to store them in cloud storage and get a URL to access them later.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Save PDF to cloud storage and get URL
output = new
{
type = "url",
url = "https://your-storage.com/"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to store PDFs in cloud storage and access them via URLs.
---
# Save your PDF to your Amazon S3 bucket — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/save-your-pdf-to-your-amazon-s3-bucket
Description: Learn how to save your PDF to your Amazon S3 bucket using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to store PDFs directly in AWS S3.
In this guide, we'll show you how to save your PDF to your Amazon S3 bucket using C# and the HttpClient library.
When generating PDFs, you might want to store them directly in Amazon S3 for easy access and management.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Save PDF to Amazon S3 bucket
output = new
{
type = "s3",
bucket = "your-bucket-name",
key = "path/to/document.pdf"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to store PDFs directly in your AWS S3 buckets.
---
# Send custom HTTP headers — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/send-custom-http-headers
Description: Learn how to send custom HTTP headers when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to customize request headers.
In this guide, we'll show you how to send custom HTTP headers when converting HTML to PDF using C# and the HttpClient library.
When converting HTML to PDF, you might need to send custom HTTP headers to access protected resources or provide additional information.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Send custom HTTP headers
headers = new
{
authorization = "Bearer token123",
"user-agent" = "MyApp/1.0"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to customize the HTTP requests sent to the source URL.
---
# Using cookies — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/using-cookies
Description: Learn how to use cookies when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to manage cookies during conversion.
In this guide, we'll show you how to use cookies when converting HTML to PDF using C# and the HttpClient library.
When converting HTML to PDF, you might need to send cookies to access authenticated content or maintain session state.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Send cookies with the request
cookies = new
{
sessionid = "abc123",
user = "john_doe"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to maintain session state when accessing protected content.
---
# Waiting for a custom element to be ready — C# / HttpClient
Source: https://pdfshift.io/guides/csharp/httpclient/waiting-for-a-custom-element-to-be-ready
Description: Learn how to wait for a custom element to be ready when converting HTML to PDF using C# and the HttpClient library. This guide offers detailed steps with code samples in C# and the HttpClient library, showing how to handle dynamic content.
In this guide, we'll show you how to wait for a custom element to be ready when converting HTML to PDF using C# and the HttpClient library.
When converting HTML containing dynamic content, you might need to wait for specific elements to be rendered before generating the PDF.
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Wait for a specific element to be ready
wait_for = "#dynamic-content.loaded"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.pdfshift.io/v3/convert/pdf", content);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
var result = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("result.pdf", result);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to ensure dynamic content is fully loaded before PDF generation.
---
# Accessing secured pages — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/accessing-secured-pages
Description: Learn how to access secured pages using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, highlighting how you can access page protected by basic authentication to convert them to PDF using PDFShift's API.
In this guide, we'll show you how to access secured page (protected by basic authentication) using C# and the HTTPWebRequest library to convert them to PDF using PDFShift's API.
When you're converting a document, you might want to access a secured page (protected by basic authentication) to convert it to PDF. This can be done by setting the `auth` parameter to the request.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// You can set a basic authentication by passing the "auth" property which contains a username and password
auth = new
{
username = "user",
password = "password"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to protect your documents from any visitors while allowing PDFShift to access the page and convert it to PDF.
---
# Adding a custom header or footer — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/adding-a-custom-header-or-footer
Description: Learn how to add custom headers and footers to your PDFs using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to customize PDF appearance with headers and footers.
In this guide, we'll show you how to add custom headers and footers to your PDFs using C# and the HTTPWebRequest library.
When generating PDFs, you might want to add custom headers and footers to your documents for branding or informational purposes.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Add custom header and footer
header = new
{
content = "Header Content
",
height = "20mm"
},
footer = new
{
content = "Footer Content
",
height = "20mm"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to add consistent branding elements to all your generated PDF documents.
---
# Adding a text watermark — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/adding-a-text-watermark
Description: Learn how to add text watermarks to your PDFs using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to apply text watermarks to protect your documents.
In this guide, we'll show you how to add text watermarks to your PDFs using C# and the HTTPWebRequest library.
When generating PDFs, you might want to add text watermarks to your documents for protection or branding purposes.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Add text watermark
watermark = new
{
text = "CONFIDENTIAL",
opacity = 0.3,
size = "20px",
color = "#000000"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to add textual protection to your documents with customizable text.
---
# Adding an image watermark — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/adding-an-image-watermark
Description: Learn how to add image watermarks to your PDFs using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to apply image watermarks to protect your documents.
In this guide, we'll show you how to add image watermarks to your PDFs using C# and the HTTPWebRequest library.
When generating PDFs, you might want to add image watermarks to your documents for protection or branding purposes.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Add image watermark
watermark = new
{
image = "https://example.com/watermark.png",
opacity = 0.5,
position = "center"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to add visual protection to your documents with custom images.
---
# Avoid conversion on error — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/avoid-conversion-on-error
Description: Learn how to avoid conversion on error using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to handle conversion errors gracefully.
In this guide, we'll show you how to avoid conversion on error using C# and the HTTPWebRequest library.
When converting documents to PDF, you might want to prevent conversion if certain errors occur to avoid generating invalid PDFs.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Prevent conversion on error
continue_on_error = false
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to fail fast when conversion issues occur.
---
# Convert HTML to PDF from a URL — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/convert-html-to-pdf-from-a-url
Description: Learn how to convert HTML from a URL to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to convert online HTML content to PDF.
In this guide, we'll show you how to convert HTML from a URL to PDF using C# and the HTTPWebRequest library.
Converting HTML from a URL to PDF is a common requirement when you want to generate PDFs from existing web content.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to easily convert any webpage to a PDF document.
---
# Convert HTML to PDF from raw HTML — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/convert-html-to-pdf-from-raw-html
Description: Learn how to convert raw HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to convert HTML content directly to PDF.
In this guide, we'll show you how to convert raw HTML to PDF using C# and the HTTPWebRequest library.
Converting raw HTML content to PDF is useful when you have HTML content that isn't hosted on a web server.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "Hello World
"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to convert HTML content directly to PDF without needing a URL.
---
# Define a time limit — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/define-a-time-limit
Description: Learn how to define a time limit for PDF conversions using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to set timeouts to prevent long-running conversions.
In this guide, we'll show you how to define a time limit for PDF conversions using C# and the HTTPWebRequest library.
When converting documents to PDF, you might want to set a timeout to prevent long-running conversions from blocking your application.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
// Set a timeout in milliseconds
request.Timeout = 30000;
var payload = new
{
source = "https://www.example.com",
// Set a timeout in seconds
timeout = 30
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to control how long a conversion can take before timing out.
---
# Exporting only a specific set of pages — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/exporting-only-a-specific-set-of-pages
Description: Learn how to export only specific pages from a document when converting to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to select specific pages for export.
In this guide, we'll show you how to export only specific pages from a document when converting to PDF using C# and the HTTPWebRequest library.
When converting documents, you might want to export only a specific range of pages rather than the entire document.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Export only pages 1-3
pages = "1-3"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to selectively export pages from multi-page documents.
---
# Generate a document with full height — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/generate-a-document-with-full-height
Description: Learn how to generate a document with full height using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to create full-height PDFs.
In this guide, we'll show you how to generate a document with full height using C# and the HTTPWebRequest library.
When converting documents to PDF, you might want to ensure the entire document height is preserved.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Generate document with full height
full_height = true
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This ensures the entire document content is included in the PDF.
---
# Loading CSS from a string — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/loading-css-from-a-string
Description: Learn how to load CSS from a string when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to apply inline CSS styling.
In this guide, we'll show you how to load CSS from a string when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML to PDF, you might want to apply CSS styling using inline CSS rather than external stylesheets.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load CSS from a string
css = "body { font-family: Arial; } h1 { color: blue; }"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to apply custom styling directly to your PDFs.
---
# Loading CSS from a URL — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/loading-css-from-a-url
Description: Learn how to load CSS from a URL when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to reference external CSS files.
In this guide, we'll show you how to load CSS from a URL when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML to PDF, you might want to reference external CSS files to maintain consistent styling.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load CSS from a URL
css = "https://example.com/styles.css"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to apply external stylesheets to your PDFs.
---
# Loading JavaScript from a string — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/loading-javascript-from-a-string
Description: Learn how to load JavaScript from a string when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to include inline JavaScript.
In this guide, we'll show you how to load JavaScript from a string when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML to PDF, you might want to include JavaScript functionality using inline code.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load JavaScript from a string
javascript = "document.body.style.backgroundColor = 'red';"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This enables dynamic behavior in your PDFs.
---
# Loading JavaScript from a URL — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/loading-javascript-from-a-url
Description: Learn how to load JavaScript from a URL when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to reference external JavaScript files.
In this guide, we'll show you how to load JavaScript from a URL when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML to PDF, you might want to reference external JavaScript files to include dynamic functionality.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Load JavaScript from a URL
javascript = "https://example.com/script.js"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to include external JavaScript libraries in your PDFs.
---
# Protecting the generated PDF — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/protecting-the-generated-pdf
Description: Learn how to protect generated PDFs with passwords using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to secure your PDF documents.
In this guide, we'll show you how to protect generated PDFs with passwords using C# and the HTTPWebRequest library.
When generating PDFs, you might want to add password protection to restrict access.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Protect the PDF with a password
protection = new
{
user_password = "user123",
owner_password = "owner123"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to secure your PDF documents with passwords.
---
# Receive a webhook event — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/receive-a-webhook-event
Description: Learn how to receive webhook events when PDF conversion is complete using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to handle asynchronous conversion notifications.
In this guide, we'll show you how to receive webhook events when PDF conversion is complete using C# and the HTTPWebRequest library.
When converting documents asynchronously, you might want to be notified when the conversion is complete via a webhook.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Set up webhook notification
webhook = new
{
url = "https://your-server.com/webhook",
secret = "your-secret-key"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to be notified when conversions are complete without polling.
---
# Save your PDF online and get back a URL — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/save-your-pdf-online-and-get-back-a-url
Description: Learn how to save your PDF online and get back a URL using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to store PDFs in cloud storage and retrieve URLs.
In this guide, we'll show you how to save your PDF online and get back a URL using C# and the HTTPWebRequest library.
When generating PDFs, you might want to store them in cloud storage and get a URL to access them later.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Save PDF to cloud storage and get URL
output = new
{
type = "url",
url = "https://your-storage.com/"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to store PDFs in cloud storage and access them via URLs.
---
# Save your PDF to your Amazon S3 bucket — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/save-your-pdf-to-your-amazon-s3-bucket
Description: Learn how to save your PDF to your Amazon S3 bucket using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to store PDFs directly in AWS S3.
In this guide, we'll show you how to save your PDF to your Amazon S3 bucket using C# and the HTTPWebRequest library.
When generating PDFs, you might want to store them directly in Amazon S3 for easy access and management.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Save PDF to Amazon S3 bucket
output = new
{
type = "s3",
bucket = "your-bucket-name",
key = "path/to/document.pdf"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to store PDFs directly in your AWS S3 buckets.
---
# Send custom HTTP headers — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/send-custom-http-headers
Description: Learn how to send custom HTTP headers when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to customize request headers.
In this guide, we'll show you how to send custom HTTP headers when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML to PDF, you might need to send custom HTTP headers to access protected resources or provide additional information.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Send custom HTTP headers
headers = new
{
authorization = "Bearer token123",
"user-agent" = "MyApp/1.0"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to customize the HTTP requests sent to the source URL.
---
# Using cookies — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/using-cookies
Description: Learn how to use cookies when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to manage cookies during conversion.
In this guide, we'll show you how to use cookies when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML to PDF, you might need to send cookies to access authenticated content or maintain session state.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Send cookies with the request
cookies = new
{
sessionid = "abc123",
user = "john_doe"
}
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to maintain session state when accessing protected content.
---
# Waiting for a custom element to be ready — C# / HTTPWebRequest
Source: https://pdfshift.io/guides/csharp/httpwebrequest/waiting-for-a-custom-element-to-be-ready
Description: Learn how to wait for a custom element to be ready when converting HTML to PDF using C# and the HTTPWebRequest library. This guide offers detailed steps with code samples in C# and the HTTPWebRequest library, showing how to handle dynamic content.
In this guide, we'll show you how to wait for a custom element to be ready when converting HTML to PDF using C# and the HTTPWebRequest library.
When converting HTML containing dynamic content, you might need to wait for specific elements to be rendered before generating the PDF.
```csharp
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var request = (HttpWebRequest)WebRequest.Create("https://api.pdfshift.io/v3/convert/pdf");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-API-Key", apiKey);
var payload = new
{
source = "https://www.example.com",
// Wait for a specific element to be ready
wait_for = "#dynamic-content.loaded"
};
var json = System.Text.Json.JsonSerializer.Serialize(payload);
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse)request.GetResponse();
// Handle errors:
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
File.WriteAllText("result.pdf", result);
}
Console.WriteLine("The PDF document was generated and saved to result.pdf");
}
catch (WebException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
```
This allows you to ensure dynamic content is fully loaded before PDF generation.
---
# Accessing secured pages — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/accessing-secured-pages
Description: Learn how to access secured pages using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, highlighting how you can access page protected by basic authentication to convert them to PDF using PDFShift's API.
In this guide, we'll show you how to access secured page (protected by basic authentication) using C# and the RestSharp library to convert them to PDF using PDFShift's API.
When you're converting a document, you might want to access a secured page (protected by basic authentication) to convert it to PDF. This can be done by setting the `auth` parameter to the request.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// You can set a basic authentication by passing the "auth" property which contains a username and password
auth = new
{
username = "user",
password = "password"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to protect your documents from any visitors while allowing PDFShift to access the page and convert it to PDF.
---
# Adding a custom header or footer — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/adding-a-custom-header-or-footer
Description: Learn how to add custom headers and footers to your PDFs using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to customize PDF appearance with headers and footers.
In this guide, we'll show you how to add custom headers and footers to your PDFs using C# and the RestSharp library.
When generating PDFs, you might want to add custom headers and footers to your documents for branding or informational purposes.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Add custom header and footer
header = new
{
content = "Header Content
",
height = "20mm"
},
footer = new
{
content = "Footer Content
",
height = "20mm"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to add consistent branding elements to all your generated PDF documents.
---
# Adding a text watermark — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/adding-a-text-watermark
Description: Learn how to add text watermarks to your PDFs using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to apply text watermarks to protect your documents.
In this guide, we'll show you how to add text watermarks to your PDFs using C# and the RestSharp library.
When generating PDFs, you might want to add text watermarks to your documents for protection or branding purposes.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Add text watermark
watermark = new
{
text = "CONFIDENTIAL",
opacity = 0.3,
size = "20px",
color = "#000000"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to add textual protection to your documents with customizable text.
---
# Adding an image watermark — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/adding-an-image-watermark
Description: Learn how to add image watermarks to your PDFs using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to apply image watermarks to protect your documents.
In this guide, we'll show you how to add image watermarks to your PDFs using C# and the RestSharp library.
When generating PDFs, you might want to add image watermarks to your documents for protection or branding purposes.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Add image watermark
watermark = new
{
image = "https://example.com/watermark.png",
opacity = 0.5,
position = "center"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to add visual protection to your documents with custom images.
---
# Avoid conversion on error — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/avoid-conversion-on-error
Description: Learn how to avoid conversion on error using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to handle conversion errors gracefully.
In this guide, we'll show you how to avoid conversion on error using C# and the RestSharp library.
When converting documents to PDF, you might want to prevent conversion if certain errors occur to avoid generating invalid PDFs.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Prevent conversion on error
continue_on_error = false
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to fail fast when conversion issues occur.
---
# Convert HTML to PDF from a URL — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/convert-html-to-pdf-from-a-url
Description: Learn how to convert HTML from a URL to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to convert online HTML content to PDF.
In this guide, we'll show you how to convert HTML from a URL to PDF using C# and the RestSharp library.
Converting HTML from a URL to PDF is a common requirement when you want to generate PDFs from existing web content.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to easily convert any webpage to a PDF document.
---
# Convert HTML to PDF from raw HTML — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/convert-html-to-pdf-from-raw-html
Description: Learn how to convert raw HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to convert HTML content directly to PDF.
In this guide, we'll show you how to convert raw HTML to PDF using C# and the RestSharp library.
Converting raw HTML content to PDF is useful when you have HTML content that isn't hosted on a web server.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "Hello World
"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to convert HTML content directly to PDF without needing a URL.
---
# Define a time limit — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/define-a-time-limit
Description: Learn how to define a time limit for PDF conversions using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to set timeouts to prevent long-running conversions.
In this guide, we'll show you how to define a time limit for PDF conversions using C# and the RestSharp library.
When converting documents to PDF, you might want to set a timeout to prevent long-running conversions from blocking your application.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
client.Timeout = 30000; // 30 seconds timeout
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Set a timeout in seconds
timeout = 30
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to control how long a conversion can take before timing out.
---
# Exporting only a specific set of pages — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/exporting-only-a-specific-set-of-pages
Description: Learn how to export only specific pages from a document when converting to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to select specific pages for export.
In this guide, we'll show you how to export only specific pages from a document when converting to PDF using C# and the RestSharp library.
When converting documents, you might want to export only a specific range of pages rather than the entire document.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Export only pages 1-3
pages = "1-3"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to selectively export pages from multi-page documents.
---
# Generate a document with full height — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/generate-a-document-with-full-height
Description: Learn how to generate a document with full height using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to create full-height PDFs.
In this guide, we'll show you how to generate a document with full height using C# and the RestSharp library.
When converting documents to PDF, you might want to ensure the entire document height is preserved.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Generate document with full height
full_height = true
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This ensures the entire document content is included in the PDF.
---
# Loading CSS from a string — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/loading-css-from-a-string
Description: Learn how to load CSS from a string when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to apply inline CSS styling.
In this guide, we'll show you how to load CSS from a string when converting HTML to PDF using C# and the RestSharp library.
When converting HTML to PDF, you might want to apply CSS styling using inline CSS rather than external stylesheets.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Load CSS from a string
css = "body { font-family: Arial; } h1 { color: blue; }"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to apply custom styling directly to your PDFs.
---
# Loading CSS from a URL — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/loading-css-from-a-url
Description: Learn how to load CSS from a URL when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to reference external CSS files.
In this guide, we'll show you how to load CSS from a URL when converting HTML to PDF using C# and the RestSharp library.
When converting HTML to PDF, you might want to reference external CSS files to maintain consistent styling.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Load CSS from a URL
css = "https://example.com/styles.css"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to apply external stylesheets to your PDFs.
---
# Loading JavaScript from a string — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/loading-javascript-from-a-string
Description: Learn how to load JavaScript from a string when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to include inline JavaScript.
In this guide, we'll show you how to load JavaScript from a string when converting HTML to PDF using C# and the RestSharp library.
When converting HTML to PDF, you might want to include JavaScript functionality using inline code.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Load JavaScript from a string
javascript = "document.body.style.backgroundColor = 'red';"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This enables dynamic behavior in your PDFs.
---
# Loading JavaScript from a URL — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/loading-javascript-from-a-url
Description: Learn how to load JavaScript from a URL when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to reference external JavaScript files.
In this guide, we'll show you how to load JavaScript from a URL when converting HTML to PDF using C# and the RestSharp library.
When converting HTML to PDF, you might want to reference external JavaScript files to include dynamic functionality.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Load JavaScript from a URL
javascript = "https://example.com/script.js"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to include external JavaScript libraries in your PDFs.
---
# Protecting the generated PDF — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/protecting-the-generated-pdf
Description: Learn how to protect generated PDFs with passwords using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to secure your PDF documents.
In this guide, we'll show you how to protect generated PDFs with passwords using C# and the RestSharp library.
When generating PDFs, you might want to add password protection to restrict access.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Protect the PDF with a password
protection = new
{
user_password = "user123",
owner_password = "owner123"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to secure your PDF documents with passwords.
---
# Receive a webhook event — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/receive-a-webhook-event
Description: Learn how to receive webhook events when PDF conversion is complete using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to handle asynchronous conversion notifications.
In this guide, we'll show you how to receive webhook events when PDF conversion is complete using C# and the RestSharp library.
When converting documents asynchronously, you might want to be notified when the conversion is complete via a webhook.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Set up webhook notification
webhook = new
{
url = "https://your-server.com/webhook",
secret = "your-secret-key"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to be notified when conversions are complete without polling.
---
# Save your PDF online and get back a URL — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/save-your-pdf-online-and-get-back-a-url
Description: Learn how to save your PDF online and get back a URL using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to store PDFs in cloud storage and retrieve URLs.
In this guide, we'll show you how to save your PDF online and get back a URL using C# and the RestSharp library.
When generating PDFs, you might want to store them in cloud storage and get a URL to access them later.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Save PDF to cloud storage and get URL
output = new
{
type = "url",
url = "https://your-storage.com/"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to store PDFs in cloud storage and access them via URLs.
---
# Save your PDF to your Amazon S3 bucket — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/save-your-pdf-to-your-amazon-s3-bucket
Description: Learn how to save your PDF to your Amazon S3 bucket using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to store PDFs directly in AWS S3.
In this guide, we'll show you how to save your PDF to your Amazon S3 bucket using C# and the RestSharp library.
When generating PDFs, you might want to store them directly in Amazon S3 for easy access and management.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Save PDF to Amazon S3 bucket
output = new
{
type = "s3",
bucket = "your-bucket-name",
key = "path/to/document.pdf"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to store PDFs directly in your AWS S3 buckets.
---
# Send custom HTTP headers — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/send-custom-http-headers
Description: Learn how to send custom HTTP headers when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to customize request headers.
In this guide, we'll show you how to send custom HTTP headers when converting HTML to PDF using C# and the RestSharp library.
When converting HTML to PDF, you might need to send custom HTTP headers to access protected resources or provide additional information.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Send custom HTTP headers
headers = new
{
authorization = "Bearer token123",
"user-agent" = "MyApp/1.0"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to customize the HTTP requests sent to the source URL.
---
# Using cookies — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/using-cookies
Description: Learn how to use cookies when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to manage cookies during conversion.
In this guide, we'll show you how to use cookies when converting HTML to PDF using C# and the RestSharp library.
When converting HTML to PDF, you might need to send cookies to access authenticated content or maintain session state.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Send cookies with the request
cookies = new
{
sessionid = "abc123",
user = "john_doe"
}
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to maintain session state when accessing protected content.
---
# Waiting for a custom element to be ready — C# / RestSharp
Source: https://pdfshift.io/guides/csharp/restsharp/waiting-for-a-custom-element-to-be-ready
Description: Learn how to wait for a custom element to be ready when converting HTML to PDF using C# and the RestSharp library. This guide offers detailed steps with code samples in C# and the RestSharp library, showing how to handle dynamic content.
In this guide, we'll show you how to wait for a custom element to be ready when converting HTML to PDF using C# and the RestSharp library.
When converting HTML containing dynamic content, you might need to wait for specific elements to be rendered before generating the PDF.
```csharp
using RestSharp;
using System.IO;
using System.Threading.Tasks;
// You can get an API key at https://pdfshift.io
var apiKey = "sk_xxxxxxxxxxxx";
var client = new RestClient("https://api.pdfshift.io/v3/convert/pdf");
var request = new RestRequest(Method.Post);
request.AddHeader("X-API-Key", apiKey);
request.AddHeader("Content-Type", "application/json");
var payload = new
{
source = "https://www.example.com",
// Wait for a specific element to be ready
wait_for = "#dynamic-content.loaded"
};
request.AddJsonBody(payload);
var response = await client.ExecuteAsync(request);
// Handle errors:
if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest)
{
throw new Exception($"Request failed with status code {response.StatusCode}");
}
File.WriteAllBytes("result.pdf", response.RawBytes);
Console.WriteLine("The PDF document was generated and saved to result.pdf");
```
This allows you to ensure dynamic content is fully loaded before PDF generation.
---
# Accessing secured pages — cUrl
Source: https://pdfshift.io/guides/curl/accessing-secured-pages
Description: Learn how to access secured pages when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to access secured pages when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Access a secured page
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com/secured", "auth": {"username": "user", "password": "pass"}}' \
-o "result.pdf"
```
With this cUrl command, you can access secured pages by providing authentication credentials. Happy coding!
```
---
# Adding a custom header or footer — cUrl
Source: https://pdfshift.io/guides/curl/adding-a-custom-header-or-footer
Description: Learn how to add custom headers and footers to your PDF documents when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to add custom headers and footers to your PDF documents when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Add a custom header and footer
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "header": {"html": "Page Header
"}, "footer": {"html": "Page Footer
"}}' \
-o "result.pdf"
```
With this cUrl command, you can add custom headers and footers to your PDF documents. Happy coding!
```
---
# Adding a text watermark — cUrl
Source: https://pdfshift.io/guides/curl/adding-a-text-watermark
Description: Learn how to add a text watermark to your PDF documents when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to add a text watermark to your PDF documents when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Add a text watermark
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "watermark": {"text": "CONFIDENTIAL"}}' \
-o "result.pdf"
```
With this cUrl command, you can add text watermarks to protect your PDF documents. Happy coding!
```
---
# Adding an image watermark — cUrl
Source: https://pdfshift.io/guides/curl/adding-an-image-watermark
Description: Learn how to add an image watermark to your PDF documents when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to add an image watermark to your PDF documents when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Add an image watermark
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "watermark": {"image": "https://example.com/logo.png"}}' \
-o "result.pdf"
```
With this cUrl command, you can add image watermarks to protect your PDF documents. Happy coding!
```
---
# Avoid conversion on error — cUrl
Source: https://pdfshift.io/guides/curl/avoid-conversion-on-error
Description: Learn how to prevent PDF conversion from happening when there are errors in the source HTML or CSS using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to avoid conversion on error using PDFShift's API. This allows you to prevent PDF generation when there are issues with the source content.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Convert HTML from a URL with error handling
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "avoid_conversion_on_error": true}' \
-o "result.pdf"
```
With this cUrl command, you can prevent PDF generation when errors occur in the source HTML or CSS. Happy coding!
```
---
# Convert an HTML document to PDF from a URL — cUrl
Source: https://pdfshift.io/guides/curl/convert-html-to-pdf-from-a-url
Description: Learn how to easily convert HTML documents to PDF from a URL using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to convert HTML documents to PDFs using PDFShift's API. This is a straightforward process that can be accomplished with just a few lines of cUrl code.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Convert HTML from a URL to PDF
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com"}' \
-o "result.pdf"
```
With this cUrl command, you can effortlessly convert HTML documents from a URL to PDF files using PDFShift's API. Happy coding!
```
---
# Convert an HTML document to PDF from raw HTML — cUrl
Source: https://pdfshift.io/guides/curl/convert-html-to-pdf-from-raw-html
Description: Learn how to easily convert HTML documents to PDF from raw HTML using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to convert HTML documents to PDFs using PDFShift's API by providing raw HTML content. This is a straightforward process that can be accomplished with just a few lines of cUrl code.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Convert raw HTML to PDF
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"html": "Hello World
This is a test document.
"}' \
-o "result.pdf"
```
With this cUrl command, you can effortlessly convert raw HTML to PDF files using PDFShift's API. Happy coding!
```
---
# Define a time limit — cUrl
Source: https://pdfshift.io/guides/curl/define-a-time-limit
Description: Learn how to define a time limit for PDF conversion using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to define a time limit for PDF conversion using PDFShift's API. This helps prevent long-running conversions from impacting your application.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Convert HTML with a time limit of 30 seconds
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "time_limit": 30}' \
-o "result.pdf"
```
With this cUrl command, you can set a time limit for PDF conversions to prevent long-running processes. Happy coding!
```
---
# Exporting only a specific set of pages — cUrl
Source: https://pdfshift.io/guides/curl/exporting-only-a-specific-set-of-pages
Description: Learn how to export only a specific set of pages when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to export only specific pages when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Export only pages 1 through 3
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "pages": "1-3"}' \
-o "result.pdf"
```
With this cUrl command, you can selectively export specific pages from multi-page documents. Happy coding!
```
---
# Generate a document with full height — cUrl
Source: https://pdfshift.io/guides/curl/generate-a-document-with-full-height
Description: Learn how to generate PDF documents with full height using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to generate PDF documents with full height using PDFShift's API. This ensures your content spans the entire page height.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Generate a document with full height
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "full_height": true}' \
-o "result.pdf"
```
With this cUrl command, you can generate PDF documents that expand to fill the full height of the page. Happy coding!
```
---
# Loading CSS from a string — cUrl
Source: https://pdfshift.io/guides/curl/loading-css-from-a-string
Description: Learn how to provide CSS styles directly as a string when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to provide CSS styles directly as a string when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Provide CSS as a string
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "css": "body { font-family: Arial; } h1 { color: blue; }"}' \
-o "result.pdf"
```
With this cUrl command, you can provide inline CSS styles for your PDF documents. Happy coding!
```
---
# Loading CSS from a URL — cUrl
Source: https://pdfshift.io/guides/curl/loading-css-from-a-url
Description: Learn how to load external CSS stylesheets when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to load external CSS stylesheets when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Load CSS from a URL
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "css": "https://example.com/styles.css"}' \
-o "result.pdf"
```
With this cUrl command, you can load external CSS files for styling your PDF documents. Happy coding!
```
---
# Loading JavaScript from a string — cUrl
Source: https://pdfshift.io/guides/curl/loading-javascript-from-a-string
Description: Learn how to provide JavaScript directly as a string when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to provide JavaScript directly as a string when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Provide JavaScript as a string
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "javascript": "document.body.style.backgroundColor = \"red\";"}' \
-o "result.pdf"
```
With this cUrl command, you can provide inline JavaScript for dynamic content in your PDF documents. Happy coding!
```
---
# Loading JavaScript from a URL — cUrl
Source: https://pdfshift.io/guides/curl/loading-javascript-from-a-url
Description: Learn how to load external JavaScript files when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to load external JavaScript files when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Load JavaScript from a URL
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "javascript": "https://example.com/script.js"}' \
-o "result.pdf"
```
With this cUrl command, you can load external JavaScript files for dynamic content in your PDF documents. Happy coding!
```
---
# Protecting the generated PDF — cUrl
Source: https://pdfshift.io/guides/curl/protecting-the-generated-pdf
Description: Learn how to protect the generated PDF with a password using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to protect the generated PDF with a password using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Protect the PDF with a password
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "protect": {"password": "mypassword"}}' \
-o "result.pdf"
```
With this cUrl command, you can password-protect your generated PDF documents. Happy coding!
```
---
# Receive a webhook event — cUrl
Source: https://pdfshift.io/guides/curl/receive-a-webhook-event
Description: Learn how to receive webhook events when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to receive webhook events when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Receive a webhook event upon completion
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "webhook": {"url": "https://yourdomain.com/webhook"}}' \
-o "result.pdf"
```
With this cUrl command, you can receive webhook notifications when PDF conversion is complete. Happy coding!
```
---
# Save your PDF online and get back a URL — cUrl
Source: https://pdfshift.io/guides/curl/save-your-pdf-online-and-get-back-a-url
Description: Learn how to save your PDF online and get back a URL when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to save your PDF online and get back a URL when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Save PDF online and get a URL
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "filename": "my-document.pdf", "webhook": {"url": "https://yourdomain.com/webhook"}}' \
-o "result.pdf"
```
With this cUrl command, you can save your PDF online and receive a URL to access it. Happy coding!
```
---
# Save your PDF to your Amazon S3 bucket — cUrl
Source: https://pdfshift.io/guides/curl/save-your-pdf-to-your-amazon-s3-bucket
Description: Learn how to save your PDF directly to an Amazon S3 bucket when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to save your PDF directly to an Amazon S3 bucket when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Save PDF to Amazon S3 bucket
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "filename": "my-document.pdf", "s3": {"bucket": "my-bucket", "key": "documents/my-document.pdf"}}' \
-o "result.pdf"
```
With this cUrl command, you can directly save your PDF to an Amazon S3 bucket. Happy coding!
```
---
# Send custom HTTP headers — cUrl
Source: https://pdfshift.io/guides/curl/send-custom-http-headers
Description: Learn how to send custom HTTP headers when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to send custom HTTP headers when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Send custom HTTP headers
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-H "User-Agent: MyCustomAgent/1.0" \
-d '{"source": "https://www.example.com"}' \
-o "result.pdf"
```
With this cUrl command, you can send custom HTTP headers to the source URL. Happy coding!
```
---
# Using cookies — cUrl
Source: https://pdfshift.io/guides/curl/using-cookies
Description: Learn how to use cookies when converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to use cookies when converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Use cookies for authentication
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "cookies": [{"name": "session", "value": "abc123"}]}' \
-o "result.pdf"
```
With this cUrl command, you can pass cookies to authenticate with protected content. Happy coding!
```
---
# Waiting for a custom element to be ready — cUrl
Source: https://pdfshift.io/guides/curl/waiting-for-a-custom-element-to-be-ready
Description: Learn how to wait for a custom element to be ready before converting HTML to PDF using cUrl. This how-to guide offers clear cUrl code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to wait for a custom element to be ready before converting HTML to PDF using PDFShift's API.
```bash
# You can get an API key at https://pdfshift.io
API_KEY="sk_xxxxxxxxxxxx"
# Wait for a custom element to be ready
curl -X POST "https://api.pdfshift.io/v3/convert/pdf" \
-H "Content-Type: application/json" \
-H "X-API-Key: ${API_KEY}" \
-d '{"source": "https://www.example.com", "wait_for": "#dynamic-content"}' \
-o "result.pdf"
```
With this cUrl command, you can delay PDF conversion until specific elements are ready. Happy coding!
```
---
# Accessing secured pages — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/accessing-secured-pages
Description: Learn how to access secured pages using Go and the Go-Resty library. This guide offers detailed steps with code samples in Go and the Go-Resty library, highlighting how you can acces page protected by basic authentication to convert them to PDF using PDFShift's API.
In this guide, we'll show you how to access secured page (protected by basic authentication) using Go and the Go-Resty library to convert them to PDF using PDFShift's API.
When you're converting a document, you might want to access a secured page (protected by basic authentication) to convert it to PDF. This can be done by setting the `auth` parameter to the request.
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/go-resty/resty/v2"
)
func main() {
// You can get an API key at https://pdfshift.io
apiKey := "sk_xxxxxxxxxxxx"
// You can set a basic authentication by passing the "auth" property which contains a username and password
params := map[string]interface{}{
"source": "https://www.example.com",
"auth": map[string]string{
"username": "user",
"password": "password",
},
}
// Marshal the parameters into JSON
jsonParams, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Create a new Resty client
client := resty.New()
// Perform the request
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("X-API-Key", apiKey).
SetBody(jsonParams).
Post("https://api.pdfshift.io/v3/convert/pdf")
if err != nil {
fmt.Println("Error performing request:", err)
return
}
// Check response status code
if resp.StatusCode() >= 400 {
fmt.Printf("Request failed with status code %d: %s\n", resp.StatusCode(), string(resp.Body()))
return
}
// Save the PDF document
err = ioutil.WriteFile("result.pdf", resp.Body(), 0644)
if err != nil {
fmt.Println("Error saving PDF document:", err)
return
}
fmt.Println("The PDF document was generated and saved to result.pdf")
}
```
This allows you to protect your documents from any visitors while allowing PDFShift to access the page and convert it to PDF.
---
# Adding a custom header or footer — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/adding-a-custom-header-or-footer
Description: Discover how to add custom headers or footers to a PDF using Go and the Go-Resty library. This in-depth guide includes Go codes that you can easily follow and quickly generate documents with PDFShift's API.
In this guide, we'll show you how to add custom headers or footers to a PDF using Go and the Go-Resty library.
We'll focus this guide on the `header` parameter, but know that the `footer` parameter works _exactly_ the same way.
The `header` parameter is an object that accepts the following parameters:
* `source`: The source of the header. It can be a URL or a raw HTML document. You can also provide some variables that we'll explain at the bottom of this guide.
* `height`: The height of the header. By default, the height is in pixels, but you can also use `mm`, `cm` or `in` as units, like `10mm`.
* `start_at`: The page number where the header should start. By default, the header will start at the first page.
**NOTE**: You must provide the full data in the header/footer, and not via a network request. Loading files such as external CSS, Js or Fonts won't work in the header or footer.
Instead, we recommend you to embed them in Base64.
Here's an example:
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/go-resty/resty/v2"
)
func main() {
// You can get an API key at https://pdfshift.io
apiKey := "sk_xxxxxxxxxxxx"
// Define the request parameters
params := map[string]interface{}{
"source": "https://en.wikipedia.org/wiki/PDF",
"header": map[string]interface{}{
"source": "Page {{ page }} over a total of {{ total }}. Made on {{ date }}
",
"height": 150,
"start_at": 2,
},
}
// Marshal the parameters into JSON
jsonParams, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Create a new Resty client
client := resty.New()
// Perform the request
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("X-API-Key", apiKey).
SetBody(jsonParams).
Post("https://api.pdfshift.io/v3/convert/pdf")
if err != nil {
fmt.Println("Error performing request:", err)
return
}
// Check response status code
if resp.StatusCode() >= 400 {
fmt.Printf("Request failed with status code %d: %s\n", resp.StatusCode(), string(resp.Body()))
return
}
// Save the PDF document
err = ioutil.WriteFile("result.pdf", resp.Body(), 0644)
if err != nil {
fmt.Println("Error saving PDF document:", err)
return
}
fmt.Println("The PDF document was generated and saved to result.pdf")
}
```
The `source` parameter present in the header/footer accepts a set of variables that will be translated when converting the document.
Here are the properties you can use:
* `{{ title }}`: The title of the document.
* `{{ url }}`: The URL of the document.
* `{{ page }}`: The current page number.
* `{{ total }}`: The total number of pages in the document.
* `{{ date }}`: The current date in the format `M/D/YY-H:MM am/pm` such as "3/16/24, 2:04 PM".
This will allow you to generate a document that looks more like a printable version of a website, with page number and customized header and footer.
---
# Adding a text watermark — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/adding-a-text-watermark
Description: Learn how to add text watermarks to your generated PDF document using Go and the Go-Resty library. With this guide, you'll be able to add watermarks on top of your generated PDFs easily with a quick request to PDFShift's API.
In this guide, we'll walk you through the process of adding text watermarks to your PDF files, using PDFShift's API.
Adding a watermark to your PDF can be done by adding the `watermark` object to your query. Adding a text allows you to customize its content and PDFShift's API provides a few properties to help you customize the visual aspect, such as the font size, color, and position.
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/go-resty/resty/v2"
)
func main() {
// You can get an API key at https://pdfshift.io
apiKey := "sk_xxxxxxxxxxxx"
params := map[string]interface{}{
"source": "https://www.example.com",
"watermark": map[string]string{
"text": "PROTECTED DOCUMENT",
"offset_x": "center",
"offset_top": "top",
},
}
// Marshal the parameters into JSON
jsonParams, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Create a new Resty client
client := resty.New()
// Perform the request
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("X-API-Key", apiKey).
SetBody(jsonParams).
Post("https://api.pdfshift.io/v3/convert/pdf")
if err != nil {
fmt.Println("Error performing request:", err)
return
}
// Check response status code
if resp.StatusCode() >= 400 {
fmt.Printf("Request failed with status code %d: %s\n", resp.StatusCode(), string(resp.Body()))
return
}
// Save the PDF document
err = ioutil.WriteFile("result.pdf", resp.Body(), 0644)
if err != nil {
fmt.Println("Error saving PDF document:", err)
return
}
fmt.Println("The PDF document was generated and saved to result.pdf")
}
```
You can customize the text watermark by applying the following properties:
* `font_size`: The size of the text. An integer value in pixels. Defaults to 16.
* `font_family` : The font family to be used. Defaults to Helvetica.
* `font_color` : The color of the text. A hexadecimal color value. Defaults to '000000'.
* `font_opacity` : The opacity of the text. A float value between 0 and 100. Defaults to 100.
* `font_bold`: A boolean to set the text as bold. Defaults to false.
* `font_italic`: A boolean to set the text as italic. Defaults to false.
You can also customize the position of the text watermark by applying the following properties:
* `offset_x`: The horizontal position of the text. Can be 'left', 'center', 'right', or a specific value in pixels. Defaults to 'center'.
* `offset_y`: The vertical position of the text. Can be 'top', 'middle', 'bottom', or a specific value in pixels. Defaults to 'center'.
For the offset positions, we accept a value in integer which will be translated to pixels, but you can also pass a unit such as 'px', 'in', 'cm', 'mm', 'pt'.
For example:
```go
params = {
"source": "https://www.example.com",
"watermark": {
"text": "PROTECTED DOCUMENT",
"offset_x": "5cm",
"offset_top": "15mm"
}
}
```
---
# Adding an image watermark — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/adding-an-image-watermark
Description: Discover how to effortlessly add image watermarks to PDFs using Go and the Go-Resty library. Our guide shows you how to add images on top of your PDF to protect your document easily. This is easily done with a simple request to PDFShift's API.
In this guide, we'll walk you through the process of adding text watermarks to your PDF files, using PDFShift's API.
Adding a watermark to your PDF can be done by adding the `watermark` object to your query.
The advantage of providing an image is that you can add a visual stamp on top of each of your pages that are generated through PDFShift.
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/go-resty/resty/v2"
)
func main() {
// You can get an API key at https://pdfshift.io
apiKey := "sk_xxxxxxxxxxxx"
params := map[string]interface{}{
"source": "https://www.example.com",
"watermark": map[string]string{
"image": "https://placekitten.com/200/300",
"offset_x": "center",
"offset_top": "top",
},
}
// Marshal the parameters into JSON
jsonParams, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Create a new Resty client
client := resty.New()
// Perform the request
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("X-API-Key", apiKey).
SetBody(jsonParams).
Post("https://api.pdfshift.io/v3/convert/pdf")
if err != nil {
fmt.Println("Error performing request:", err)
return
}
// Check response status code
if resp.StatusCode() >= 400 {
fmt.Printf("Request failed with status code %d: %s\n", resp.StatusCode(), string(resp.Body()))
return
}
// Save the PDF document
err = ioutil.WriteFile("result.pdf", resp.Body(), 0644)
if err != nil {
fmt.Println("Error saving PDF document:", err)
return
}
fmt.Println("The PDF document was generated and saved to result.pdf")
}
```
The "image" parameter for the watermark can be used in two different values:
* URL : A full URL to an image that will be used as the watermark.
* Base64 : A base64 encoded image that will be used as the watermark.
Note that you can also rotate the image by passing the `rotate` parameter as a degree (or negative degree)
You can also customize the position of the text watermark by applying the following properties:
* `offset_x`: The horizontal position of the text. Can be 'left', 'center', 'right', or a specific value in pixels. Defaults to 'center'.
* `offset_y`: The vertical position of the text. Can be 'top', 'middle', 'bottom', or a specific value in pixels. Defaults to 'center'.
For the offset positions, we accept a value in integer which will be translated to pixels, but you can also pass a unit such as 'px', 'in', 'cm', 'mm', 'pt'.
For example:
```json
params = {
"source": "https://www.example.com",
"watermark": {
"text": "PROTECTED DOCUMENT",
"offset_x": "5cm",
"offset_top": "15mm"
}
}
```
---
# Avoid the conversion on error when loading the document — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/avoid-conversion-on-error
Description: Learn how to avoid the conversion on error when loading the document using Go and the Go-Resty library and relies on the PDFShift's API.
In this guide, we'll show you how to abort the conversion when loading the distant source does not return a 2XX response.
When you're converting a document, you might want to avoid the conversion on error when loading the document. This can be done by setting the `raise_for_status` parameter to `True` in the request.
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/go-resty/resty/v2"
)
func main() {
// You can get an API key at https://pdfshift.io
apiKey := "sk_xxxxxxxxxxxx"
params := map[string]interface{}{
"source": "https://www.httpstat.us/404",
"raise_for_status": true,
}
// Marshal the parameters into JSON
jsonParams, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Create a new Resty client
client := resty.New()
// Perform the request
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("X-API-Key", apiKey).
SetBody(jsonParams).
Post("https://api.pdfshift.io/v3/convert/pdf")
if err != nil {
fmt.Println("Error performing request:", err)
return
}
// Check response status code
if resp.StatusCode() >= 400 {
fmt.Printf("Request failed with status code %d: %s\n", resp.StatusCode(), string(resp.Body()))
return
}
// Save the PDF document
err = ioutil.WriteFile("result.pdf", resp.Body(), 0644)
if err != nil {
fmt.Println("Error saving PDF document:", err)
return
}
fmt.Println("The PDF document was generated and saved to result.pdf")
}
```
Passing `raise_for_status` to `true` will ensure that if PDFShift can not load your document, the conversion will fail with an error.
---
# Convert an HTML document to PDF from a URL — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/convert-html-to-pdf-from-a-url
Description: Learn how to easily convert HTML documents to PDF from a URL using Go and the Go-Resty library. This how-to guide offers clear Go code examples that show developers how to implement this using the PDFShift API.
In this guide, we'll show you how to convert HTML documents to PDFs using PDFShift's API. This is a straightforward process that can be accomplished with just a few lines of Go code.
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/go-resty/resty/v2"
)
func main() {
// You can get an API key at https://pdfshift.io
apiKey := "sk_xxxxxxxxxxxx"
params := map[string]interface{}{
"source": "https://www.exemple.com",
}
// Marshal the parameters into JSON
jsonParams, err := json.Marshal(params)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Create a new Resty client
client := resty.New()
// Perform the request
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetHeader("X-API-Key", apiKey).
SetBody(jsonParams).
Post("https://api.pdfshift.io/v3/convert/pdf")
if err != nil {
fmt.Println("Error performing request:", err)
return
}
// Check response status code
if resp.StatusCode() >= 400 {
fmt.Printf("Request failed with status code %d: %s\n", resp.StatusCode(), string(resp.Body()))
return
}
// Save the PDF document
err = ioutil.WriteFile("result.pdf", resp.Body(), 0644)
if err != nil {
fmt.Println("Error saving PDF document:", err)
return
}
fmt.Println("The PDF document was generated and saved to result.pdf")
}
```
With this Go script, you can effortlessly convert HTML documents from a URL to PDF files using PDFShift's API. Happy coding!
---
# Convert an HTML document to PDF from raw HTML — Go / Go-Resty
Source: https://pdfshift.io/guides/go/go-resty/convert-html-to-pdf-from-raw-html
Description: Learn how to to convert raw HTML document to PDF using Go and the Go-Resty library. Our guide will explain you how to quickly convert documents with PDFShift's API.
In this guide, we'll show you how to convert an HTML document to PDF using Go and the Go-Resty library.
Providing the HTML document as raw as a lot of great advantages :
* It avoids PDFShift to make a network request to fetch the HTML document.
* It allows you to convert HTML documents that are not publicly accessible.
* It improves the speed of the conversion
If, on top of that, you can provide the styles and javascript also inline in the document (`