Giter Site home page Giter Site logo

ilovepdf-net's Introduction

iLovePDF

CI NuGet Downloads NuGet ILove_PDF_test on fuget.org GitHub

iLovePDF Api - C# Library

A library in C# for iLovePDF Api You can sign up for a iLovePDF account at https://developer.ilovepdf.com

Develop and automate PDF processing tasks like Compress PDF, Merge PDF, Split PDF, convert Office to PDF, PDF to JPG, Images to PDF, add Page Numbers, Rotate PDF, Unlock PDF, stamp a Watermark and Repair PDF. Each one with several settings to get your desired results.

Requirements

Minimum .NET Framework 4.5

Install

You can install library from Nuget

PM-> Install-Package ILove_PDF

Simple usage looks like:

var lovePdfAPi = new LovePdfApi("project_public_id", "project_secret_key");

var task = lovePdfAPi.CreateTask<CompressTask>();
var file = task.AddFile("file1.pdf")
var time = task.Process();
task.DownloadFile("directory-to-download");

Documentation

Please see https://developer.ilovepdf.com/docs for up-to-date documentation.

License

The code is available as open source under the terms of the MIT License.

ilovepdf-net's People

Contributors

abberdeen avatar dependabot[bot] avatar marcogrossisas avatar mariomash avatar olegra avatar teamcrombie avatar thorvaldd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ilovepdf-net's Issues

Task.Result may result in deadlocks

The RequestHelper class is currently hiding some calls to Task.Result when processing requests. Task.Result blocks the current thread until the task completes, which can cause deadlocks in many common scenarios. Take the following example from RequestHelper.Download:

response = client.SendAsync(request).Result;

The easiest correct pattern here would be:

var downloadTask = Task.Run(() => client.SendAsync(request));
downloadTask.Wait();
response = downloadTask.Result;

ILove PDF - Compress PDF issue

We try to integrate your API for compress PDF but we found error that : 'Could not load file or assembly for StringInterpolationBridge' . Please help us asap so we can proceed further..

Provide SDK version compatible with .NET Framework 4.5

After some experimenting, I found that when I add the nuget package (and not trying to compile the project myself), all works like a charm.
However, you have one dependency to a component that requires .NET 4.6. This prevents us from using the component from Windows PowerShell (as this component apparently uses .NET 4 or 4.5).
When I run the same code sample in the cross-platform PowerShell 7, it works perfectly well so I assume it must be related to the dependency (which returns the exception that “response” is NULL).
Being compatible with Windows PowerShell is somewhat important as this is the default scripting environment on Windows and widely used in the industry.

Convert PDF to PDFA-1a

Good morning,

regarding the conversion indicated in the object, I am trying the following code c#:

var TaskParams = new PdfToPdfAParams();

var taskPDFtoPDFA = api.CreateTask();

// Add files to task for upload
var file1 = taskPDFtoPDFA.AddFile(@"file1.pdf");

// Execute the task
taskPDFtoPDFA.Process(new PDFtoPDFAParams(Conformance = "pdfa-1a", AllowDowngrade = false));

// Download the package files
taskPDFtoPDFA.DownloadFile();

but when i go to run the process, i get the following error:

"PdfToPdfAParams" does not contain a constructor that accepts 2 arguments.

How can I solve it?

Thanks and best regards, Annibale.

The library throw an exception during the creation of the task <OfficeToPdfTask>

I'm trying to use the service but with this code ( .net framework 4.7.2)

`
var docx = File.ReadAllBytes("../../word/result.docx");

        var api = new LovePdfApi(projectKey, secretKey);

        var taskConvertOffice = api.CreateTask<OfficeToPdfTask>();
        // Add files to task for upload
        var file1 = taskConvertOffice.AddFile(docx);
        // Execute the task
        taskConvertOffice.Process();
        // Download the package files
        var pdf = taskConvertOffice.DownloadFileAsByteArrayAsync().Result;

        File.WriteAllBytes("../../word/result.pdf", pdf);

`

during the line

var taskConvertOffice = api.CreateTask<OfficeToPdfTask>();

throw this exception :
image

I'm doing something wrong ?

Migrate to FxCopAnalyzers and fix warnings

Current post-build version of static analysis is outdated and have to be upgraded to FxCopAnalyzer based approach (build-only Roslyn-based NuGet package). And of course we should make build 'clear' and fix all warnings.

NullReference error when calling .Next<CompressTask>(); method

Hi folks,

I’m using iLovePDF to convert docx to pdf + compress pdf and I'm facing an exception when I call the Next() method but I’m not sure if my implementation is correct, and I could not find any examples regarding this use case (or any other using the /next endpoint).

The file is converted successfully, but an exception is raised when calling the .Next

var lovePdfAPi = new LovePdfApi("xxx", "xxx");

var convertTask = lovePdfAPi.CreateTask<LovePdf.Model.Task.OfficeToPdfTask>();
var file = convertTask.AddFile(new Uri("https://file-examples.com/wp-content/uploads/2017/02/file-sample_1MB.docx"));
var time = convertTask.Process();
           
var compressTask = convertTask.Next<CompressTask>();
compressTask.Process();

var compress_async = compressTask.DownloadFileAsByteArrayAsync();
compress_async.Wait();
var file_result = compress_async.Result;

System.IO.File.WriteAllBytes(DateTime.Now.ToFileTime() + ".pdf", file_result);//salva cada pdf encontrado


Console.Write(file_result.Length.ToString() + " total bytes returned");

This is my code, the conversion was working fine, but when I added the convertTask.Next() it raised the exception “System.NullReferenceException: 'Object reference not set to an instance of an object.'":

After some further investigation, I’ve decided to reference the Source Code of the .NET API Library and seems like the error happens because the API response is 200 but the response body is returning “null” :

RequestHelper.cs
image

Is something missing in my code? Thanks in advance!

Exception thrown - Could not load file or assembly StringInterpolationBridge

◢ | $exception | {"Could not load file or assembly 'StringInterpolationBridge, Version=0.9.1.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.":"StringInterpolationBridge, Version=0.9.1.0, Culture=neutral, PublicKeyToken=null"} | System.IO.FileNotFoundException

var lovePdfAPi = new LovePdfApi("xxx", "yyy");
var task = lovePdfAPi.CreateTask<RepairTask>(); // exception here at LovePdf.Core.LovePdfApi.CreateTask[T]()
var file = task.AddFile(fullFilePath);
var time = task.Process();
task.DownloadFile();

I've added this code after installing the Nuget package into an existing project .NET 4.7.2.
I also used the same code in a few new projects using .NET 4.5, 4.6 and 4.8 just to make sure it's not the version. Same error message.
Using VS 2017 fully updated as of posting. Using free tier account at iLovePdf.

Use cached HttpClient instance in SDK

Current usage pattern for HttpClient class is incorrect - we shouldn't create new instance of this class for each new call instead it should be created and configured only once for single domain.

ILovePDF Compress - File extension not supported Exception

Hi,
I am using ILovePDF API and trying to add a byte array in AddFile() function by using the below code.
var file1 = taskCompress.AddFile(flupload.FileBytes);

Above I am using ASP.net file uploader control. And I am getting the below error, Please help me.

An exception of type 'LovePdf.Model.Exception.UploadException' occurred in ILovePdf.dll but was not handled in user code Additional information: {"error":{"type":"UploadError","message":"Request can't be processed successfully","code":400,"param":{"file":["File extension not supported."],"type":["InvalidExtension"]}}}

Hope I got your usual quick response thanks in advance.

Duplicate Enum Member Keys on DocumentPageSizes

https://github.com/ilovepdf/ilovepdf-net/blame/79f23d51b30b21074cc3785e1af98623f41a3439/src/ILovePDF/Model/Enums/DocumentPageSizes.cs#L8

Enum has 2 members with the same Key = A5

[EnumMember(Value = "A5")] A5,
[EnumMember(Value = "A5")] A6,

which when attempting to set the page size on the request the InitialValueHelper throws an exception on GetInitialValues

https://github.com/ilovepdf/ilovepdf-net/blob/master/src/ILovePDF/Helpers/InitialValueHelper.cs

Watermark image not working in .NET SDK

As per the documentation I have built this .NET SDK code:

var watermark = new LovePdf.Core.LovePdfApi("", "");
var watermarkTask = watermark.CreateTask();
var watermarkParameters = new WaterMarkParams(new WatermarkModeImage(@"C:\Users...."));
//var watermarkParameters = new WaterMarkParams(new WatermarkModeText("WOLOLOLO"));
watermarkParameters.Transparency = 25;
watermarkParameters.Mode = LovePdf.Model.Enums.WaterMarkModes.Image;
//watermarkParameters.TryPdfRepair = true;
watermarkParameters.HorizontalPosition = LovePdf.Model.Enums.WaterMarkHorizontalPositions.Middle;
watermarkParameters.VerticalPosition = LovePdf.Model.Enums.WaterMarkVerticalPositions.Center;

        watermarkTask.AddFile(@"C:\Users\...pdf");

      
        watermarkTask.Process(watermarkParameters);
        watermarkTask.DownloadFile(@"C:\Users\...\Downloads\");

I always get an error saying that I have submitted a bad request. The same code, however, works for the text mode. Please suggest.

Check source via static code analysis

PVS Studio provides static C# code analysis for OSS project for free so we can check this codebase using this tool and report found problems here or in separate issues.

Cleanup code using ReSharper

There is a lot of warnings about possible code cleanup/improvements generated by the R# tool - we can fix all of them for better support experience.

Download file converted to PDFA-1A

Good morning,

when I go to execute the following statement:

taskPDFtoPDFA.DownloadFile (@ "D: \ test_conversion_PDFA_1A");

I get the following exception:

{"The response status code does not indicate the success of the operation: 400 (Bad Request)."} System.Exception {System.Net.Http.HttpRequestException}.

The code I use is this:

var TaskParams = new PdfToPdfAParams ();
var taskPDFtoPDFA = api.CreateTask ();
string path = System.Web.HttpContext.Current.Server.MapPath ("Upload / PDF_text_edited"). ToString ();
FileStream ReadPDF = new FileStream (path, FileMode.Open);
byte [] Buffer = new byte [(int) ReadPDF.Length];
ReadPDF.Read (Buffer, 0, (int) ReadPDF.Length);
ReadPDF.Close ();
var file1 = taskPDFtoPDFA.AddFile (Buffer);
taskPDFtoPDFA.Process (new PdfToPdfAParams
                {
                    Conformance = ConformanceValues.PdfA1A
                });

taskPDFtoPDFA.DownloadFile (@ "D: \ prova_conversione_PDFA_1A");

I can't understand where the error is.

Thanks and best regards

Token is not refreshed if expired

Hi

I tried to use this lib on a testing project. It works great at first but after some times (more than 2hours), I get HTTP errors (401 : Unauthorize) without any reason.
PS : I'm using autofact to inject the lib.

I tried different things to fix the issue but I think there is a problem with your method that verify if the token is valid.

https://github.com/ilovepdf/ilovepdf-net/blob/master/ILovePDF/ILovePDF/Core/RequestHelper.cs

        private Boolean isExpiredGwt()
        {
            try
            {
                JWT.Decode(Gwt, _privateKey, JwsAlgorithm.HS256);
                return false;
            }
            catch (Exception)
            {
                return true;
            }
        }

It seems that the "JWT.Decode" function doesn't check if the token is expired, it only check if the token is valid on himself
https://github.com/dvsekhvalnov/jose-jwt/blob/1f49ec31134e297c1c3ae9fbd2234181f25bd43d/jose-jwt/JWT.cs

I forked the project to modify the code and generate token for each call and it seems to work like that

        private void addAuthorizationHeader(HttpClient httpClient)
        {
              Gwt = getJwt();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Gwt);
         }

A better fix would be to verify if the decoded token is valid thanks to his "exp" property.

Use GitHub Action for CI/CD

I've already created GitHub Action for building binaries but we can also automate the release creation process and NuGet package publishing.

Request can't be processed successfully - htmlpdf

I have this problem with laravel

Ilovepdf\Exceptions\UploadException
Request can't be processed successfully (Cloud File is not a valid URL.)

image

My code:

$ilovepdf = new Ilovepdf(config('services.ilovepdf.public_key'), config('services.ilovepdf.secret_key'));
$task = $ilovepdf->newTask('htmlpdf');
$file = $task->addFileFromUrl($url);
$task->execute();

And the URL is: https://9396-200-83-165-172.ngrok.io/tickets/pdf/59/HEcy6dDvWhKTTURsGUbTc-ANl3-PG0Y5hVMksuoiq-ehBbzkn5WS6FVfxMy6XbpfsHU32sPLIidLFZ_RtbEA1w==

Update XML comments for public items

VS uses XML comments for building IntelliSense help topics and we should review all public classes/methods and check if provided help is really useful.

try-catch happens too soon

When a network error happens, the httpClient.SendAsync(..).Result can crash before the response and the responseContent variables are set. The parseRequestErrors then crashes with a Object not set as and instance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.