Split pdf through .net rest api

Hii, I am trying to split pdf through .net rest api. First I uploaded a pdf on saaspose server and then tried to split it. But when I am sending the request to split it is giving 400(Bad Request) exception. Yesterday It was working fine but today it is giving "Bad Request" exception. Pls tell me what I am doing wrong or if there is any problem from server side. If you have any demo code to split pdf through .net rest api , pls provide me , I really need it this time.

Hi Anand,


Thanks for contacting support.

I have moved this query to respective forum and my fellow worker will further look into the details of this problem and will keep you posted on the status of correction.

We apologize for this inconvenience.

Hi Anand,


Thank you for your interest in our Aspose.Pdf for Cloud product. I did not observe any issue with the split pdf feature through Aspose.Pdf for Cloud .NET REST API. Bad request (400) means improperly-formatted request. Could you please share your source code here in this thread? We will take a closer look and guide you accordingly.

Hii,

Here is my code to split the pdf through which I am getting bad request error. Please check this and if there is any issue please inform me. This is for Windows 8 app.

public void SplitFile()

{

string signedURI = Sign(Constants.SPLITURI, Constants.APP_SID, Constants.APP_KEY);

ProcessCommand(signedURI, “POST”);

}

private string Sign(string url, string appSID, string appKey)

{

try

{

[//progressBar.Value](https://progressbar.value/) = 40;

// Add appSID parameter.

UriBuilder builder = new UriBuilder(url);

if (builder.Query != null && builder.Query.Length > 1)

{

builder.Query = builder.Query.Substring(1) + “&appSID=” + appSID;

}

else

{

builder.Query = “appSID=” + appSID;

}

// Remove final slash here as it can be added automatically.

builder.Path = builder.Path.TrimEnd(’/’);

// Compute the hash.

byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(appKey);

var crypt = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);

var buffer = CryptographicBuffer.ConvertStringToBinary(builder.Uri.AbsoluteUri, BinaryStringEncoding.Utf8);

var keyBuffer = CryptographicBuffer.ConvertStringToBinary(appKey, BinaryStringEncoding.Utf8);

var key = crypt.CreateKey(keyBuffer);

var sigBuffer = CryptographicEngine.Sign(key, buffer);

string signature = CryptographicBuffer.EncodeToBase64String(sigBuffer);

//// Remove invalid symbols.

signature = signature.TrimEnd(’=’);

signature = WebUtility.UrlEncode(signature);

// Convert codes to upper case as they can be updated automatically.

signature = System.Text.RegularExpressions.Regex.Replace(signature, “%[0-9a-f]{2}”, e => e.Value.ToUpper());

[//progressBar.Value](https://progressbar.value/) = 50;

// Add the signature to query string.

return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);

}

catch (Exception exception)

{

this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>

{

this.tbkStatusMessage.Text = exception.Message;

this.stbStatusMessage.Begin();

App.MainViewModel.IsVisible = false;

this.lvPdfList.IsEnabled = true;

this.appBarMainPage.Visibility = Windows.UI.Xaml.Visibility.Visible;

});

throw new Exception(exception.Message);

}

}

public async void ProcessCommand(string strURI, string strHttpCommand)

{

try

{

Uri address = new Uri(strURI);

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);

request.Method = strHttpCommand;

request.ContentType = “application/json”;

byte[] inData = new byte[4096];

request.BeginGetRequestStream(delegate(IAsyncResult req)

{

var outStream = request.EndGetRequestStream(req);

outStream.Write(inData, 0, inData.Length);

request.BeginGetResponse(new AsyncCallback(GetResponseSplitCallback), request);

}, null);

}

catch (System.Net.WebException webex)

{

throw new Exception(webex.Message);

}

catch (Exception Ex)

{

throw new Exception(Ex.Message);

}

}

private async void GetResponseSplitCallback(IAsyncResult asynchronousResult)

{

if (Constants.IsInternet())

{

try

{

HttpWebRequest asyncState = (HttpWebRequest)asynchronousResult.AsyncState;

HttpWebResponse httpWebResponse = (HttpWebResponse)asyncState.EndGetResponse(asynchronousResult);

Stream reader = httpWebResponse.GetResponseStream();

//CookieCollection cookie = httpWebResponse.Cookies;

string splitMessage = httpWebResponse.StatusCode.ToString();

StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream());

string splitPdfList = responseStream.ReadToEnd();

string[] splitedListArray = splitPdfList.Split(’[’);

string splitedList = splitedListArray[1].Insert(0, “{“pdfLists”:[”);

int listLength = splitedList.Length;

string finalSplitedJson = splitedList.Remove(listLength - 1);

RootObject list = JsonHelper.Deserialize(finalSplitedJson);

[//PdfListViewModel.PDFList](https://pdflistviewmodel.pdflist/) = list.pdfLists.ToObservableCollection();

foreach (SplitPdf splitPage in list.pdfLists)

{

Constants.SPLITFILENAME = System.IO.Path.GetFileName(splitPage.Href);

//build URI to download split pages

string strURI = “http://api.saaspose.com/v1.0/storage/file/” + Constants.SPLITFILENAME;

//sign URI

string signedURI = Sign(strURI,Constants.APP_SID,Constants.APP_KEY);

string outputPath = @“C:\Users\anand\Downloads”+Constants.SPLITFILENAME;

//save split PDF pages as PDF

SavePdf(signedURI,“GET”,outputPath);

}

if (splitMessage == “OK”)

{

this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>

{

this.tbkStatusMessage.Text = “File has Splited Successfully.”;

this.stbStatusMessage.Begin();

[//progressBar.Value](https://progressbar.value/) = 100;

});

}

else

{

this.tbkStatusMessage.Text = “Error in uploading file”;

this.stbStatusMessage.Begin();

}

}

catch (Exception exception)

{

this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>

{

this.tbkStatusMessage.Text = "Request Cannot be processed for now data ambiguity occurred ";

this.stbStatusMessage.Begin();

});

}

finally

{

this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>

{

App.MainViewModel.IsVisible = false;

this.lvPdfList.IsEnabled = true;

this.appBarMainPage.Visibility = Windows.UI.Xaml.Visibility.Visible;

});

}

}

else

{

this.tbkStatusMessage.Text = “No internet connection available.”;

this.stbStatusMessage.Begin();

App.MainViewModel.IsVisible = false;

this.lvPdfList.IsEnabled = true;

this.appBarMainPage.Visibility = Windows.UI.Xaml.Visibility.Visible;

}

}

Hi Anand,


Please accept our apologies for the delay. We are working over your query and will get back to you as soon as possible.

Hi Anand,

Thank you for sharing sample project. I'm preparing an environment to test and run your sample project. I'll update you at the start of next week. I'm sorry for your inconvenience.

Hi Anand,


Thanks for your patience. I could not observe any issue with the provided sample project. I’m able to split PDF file. It is quite possible that you are attempting to PUT a file which is too large results in an HTTP status code 400 Bad Request. Regarding file size, with an evaluation account, you can upload files of size up to 1 MB. However, with our paid plans you can upload larger files. Please try using a small size document and let me know how it goes on your side.

Hi,

Thanks for your support. Now my code is working fine for splitting a pdf. Now I want to add signatures in a pdf file. I used the code that is given on aspose website, but it is not working correctly. Can you please tell me how your code works for adding signatures in a pdf through .net rest api. If you can give me any demo code, it will be very beneficial for me.

Here is my code that I wrote for adding signature in pdf. This is the app for windows 8

private void btnSignPdf_Click(object sender, RoutedEventArgs e)
{
App.MainViewModel.IsVisible = true;
BottomAppBar.IsOpen = true;
grdSignFiles.Visibility = Visibility.Collapsed;

Signature signature = new Signature();
signature.SignaturePath = pnSignPath.Text;
signature.Password = pnSignPassword.Text;
signature.SignatureType = SignatureType.PKCS7;
signature.FormFieldName = pnSignFormFieldName.Text;
signature.Reason = pnSignReason.Text;
signature.Contact = pnSignContact.Text;
signature.Location = pnSignLocation.Text;
[//signature.Date](https://signature.date/) = new DateTimeSignature(2012, 8, 1, 12, 15, 0);
signature.Authority = pnSignAuthority.Text;
signature.Appearance = “Image1.jpg”;
signature.Rectangle = new PdfConverterPro.Classes.Rectangle(100, 100, 400, 100);
signature.Visible = true;

//build URI to sign PDF
string strJSON = JsonConvert.SerializeObject(signature);
string strURI = Constants.MOVEURI + Constants.STR_FILE_NAME + “/sign”;
string signedURI = Sign(strURI, Constants.APP_SID, Constants.APP_KEY);
SignPdfProcessCommand(signedURI, “POST”, strJSON);
}

public async void SignPdfProcessCommand(string strURI, string strHttpCommand, string strContent)
{
try
{
byte[] arr = System.Text.Encoding.UTF8.GetBytes(strContent);

Uri address = new Uri(strURI);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
request.Method = strHttpCommand;
request.ContentType = “application/json”;

byte[] inData = new byte[arr.Length];
Stream dataStream = await request.GetRequestStreamAsync();
dataStream.Write(arr, 0, arr.Length);
dataStream.Flush();

string downloadedURI = Constants.UPLOAD_URI + Constants.STR_FILE_NAME;
string signedURI = Sign(downloadedURI, Constants.APP_SID, Constants.APP_KEY);
SavePdf(signedURI, “GET”);
}
catch (System.Net.WebException webex)
{
throw new Exception(webex.Message);
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}

public async void SavePdf(string strURI, string strHttpCommand)
{
try
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Uri address = new Uri(strURI);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
request.Method = strHttpCommand;
request.BeginGetResponse(new AsyncCallback(GetResponseSaveSplitPdfCallback), request);
});
}
catch (System.Net.WebException webex)
{
throw new Exception(webex.Message);
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}

private async void GetResponseSaveSplitPdfCallback(IAsyncResult asynchronousResult)
{
if (Constants.IsInternet())
{
try
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
HttpWebRequest asyncState = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse httpWebResponse = (HttpWebResponse)asyncState.EndGetResponse(asynchronousResult);
Stream responseStream = httpWebResponse.GetResponseStream();

//Code to select the folder in which downloaded files will be saved
StorageFile myMerge = null;
if (Constants.TASK == “split”)
{
if (Constants.DOWNLOADPDFCOUNT > 0)
{
myMerge = await folder.CreateFileAsync(string.Format(downPdf, index++), CreationCollisionOption.ReplaceExisting);
}
else
{
var folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("<em>");
folder = await folderPicker.PickSingleFolderAsync();
myMerge = await folder.CreateFileAsync(string.Format(downPdf, index++), CreationCollisionOption.ReplaceExisting);
Constants.DOWNLOADPDFCOUNT++;
}
}
else
{
var folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("</em> ");
var folder = await folderPicker.PickSingleFolderAsync();
myMerge = await folder.CreateFileAsync(string.Format(downPdf, index++), CreationCollisionOption.ReplaceExisting);
}

App.MainViewModel.IsVisible = true;
byte[] buffer = new byte[8 * 1024];
int len;
using (var ostream = await myMerge.OpenStreamForWriteAsync())
{
while ((len = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
await ostream.WriteAsync(buffer, 0, len);
}
}
if (Constants.TASK == “split”)
{
progressBar.Value = 100;
App.MainViewModel.IsVisible = false;
this.tbkStatusMessage.Text = Constants.SPLITED_SUCCESSFUL;
this.stbStatusMessage.Begin();
}
else if (Constants.TASK == “move”)
{
progressBar.Value = 100;
App.MainViewModel.IsVisible = false;
this.tbkStatusMessage.Text = Constants.MOVED_SUCCESSFUL;
this.stbStatusMessage.Begin();
}
else if (Constants.TASK == “merge”)
{
progressBar.Value = 100;
App.MainViewModel.IsVisible = false;
this.tbkStatusMessage.Text = Constants.MERGE_SUCCESSFUL;
this.stbStatusMessage.Begin();
}
else if (Constants.TASK == “sign”)
{
progressBar.Value = 100;
App.MainViewModel.IsVisible = false;
this.tbkStatusMessage.Text = Constants.SIGN_SUCCESSFUL;
this.stbStatusMessage.Begin();
}

});
}
catch (Exception exception)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
this.tbkStatusMessage.Text = Constants.REQUEST_FAIL;
this.stbStatusMessage.Begin();
});
}
finally
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
App.MainViewModel.IsVisible = false;
this.lvPdfList.IsEnabled = true;
this.appBarMainPage.Visibility = Windows.UI.Xaml.Visibility.Visible;
});
}
}
else
{
this.tbkStatusMessage.Text = Constants.NO_INTERNET_CONNECTION;
this.stbStatusMessage.Begin();
App.MainViewModel.IsVisible = false;
this.lvPdfList.IsEnabled = true;
this.appBarMainPage.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}

And I created a “Signature.cs” class file also as your website is showing.
Please tell me where I am doing mistake. I will be very thankful if you can give me a demo code for adding signature in pdf.

Thanks…

Hi Anand,


Thanks for your inquiry. Could you please share your sample input documents here in this thread? We will take a closer look and guide you accordingly.

Hi,


I need to add signatures in any pdf of user. I am attaching a sample pdf document here. Please guide me how I can add signatures in it through .net rest api.
Hi Anand,

Thank you for sharing the sample PDF document. I'm sorry to share with you that the sign resource is throwing an error message. It seems an issue with a REST API. I have logged this problem under ticket id SAASPDF-102 in our issue tracking system. We will soon investigate the cause of error message and you will be notified as soon as it is fixed. We're sorry for your inconvenience.

Hi,


I am trying to upload multiple pdfs together for merging them. But only two pdfs are getting upload and after that nothing happens. If I upload only two pdf for merging it works fine. But in case of more pdfs, still only two pdf gets upload. I dont know why its happening. Could you please help me out , how I can upload multiple pdfs together on aspose server.

Following is the code that I am using to upload pdfs on server…
===================Getting all the selected pdf==========================
foreach (PDFListView item in lvPdfList.SelectedItems)
{

totalPdfCount = lvPdfList.SelectedItems.Count;
selectedPdfList.Add(item);

int pdfIndex = i;
var pdfStream = App.MainViewModel.PDFListViewlist[pdfIndex].PDFStreamList.CloneStream();

string[] strFileName = item.Data.Split(’\n’);

string strURI = Constants.UPLOAD_URI + strFileName[0];//Constants.STR_FILE_NAME;
signedUploadURI = Sign(strURI, Constants.APP_SID, Constants.APP_KEY);
if (lvPdfList.SelectedItems.Count > 1 || lvPdfListSnap.SelectedItems.Count > 1)
{
await UploadFileBinary(pdfStream.AsStream(), signedUploadURI, “PUT”);
autoResetEvent.WaitOne();
}
else
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
this.tbkStatusMessage.Text = Constants.UPLOAD_TWO_FILE;
this.stbStatusMessage.Begin();
App.MainViewModel.IsVisible = false;
this.lvPdfList.IsEnabled = true;
this.appBarMainPage.Visibility = Windows.UI.Xaml.Visibility.Visible;
});
}
i++;
}

====================Uploading pdf on server==========================
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(uploadUrl);
request.Method = strHttpCommand;
request.ContentType = “application/x-www-form-urlencoded”;
request.UseDefaultCredentials = true;

byte[] inData = new byte[streamContent.Length];
int bytesRead = streamContent.Read(inData, 0, (int)streamContent.Length);

request.BeginGetRequestStream(delegate(IAsyncResult req)
{
var outStream = request.EndGetRequestStream(req);
outStream.Write(inData, 0, inData.Length);
request.BeginGetResponse(new AsyncCallback(GetUploadResponseCallback), request);
}, null);


==========================Upload Response Method======================
private async void GetUploadResponseCallback(IAsyncResult asynchronousResult)
{
if (Constants.IsInternet())
{
try
{
autoResetEvent.Set();
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
HttpWebRequest asyncState = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse httpWebResponse = (HttpWebResponse)asyncState.EndGetResponse(asynchronousResult);
string uploadMessage = httpWebResponse.StatusCode.ToString();
}
}
}
}


Hi Anand,

You need to properly close all streams as you can see in the UploadFileBinary method at https://github.com/asposeforcloud/Aspose_Cloud_SDK_For_.NET/blob/master/AsposeCloud.SDK-for-.NET-master/AsposeCloud.SDK/Common/Utils.cs. Please use using block for all streams to resolve this issue.

Also, you can use the following code in the exception part of your ProcessCommand method to force this method to throw proper exceptions instead of bad request or internal server errors.

catch (System.Net.WebException webex)

{

string message = webex.Message;

if (webex.Response != null)

{

if (webex.Response.ContentLength != 0)

{

using (Stream stream = webex.Response.GetResponseStream())

{

using (StreamReader reader = new StreamReader(stream))

{

message = reader.ReadToEnd();

}

}

}

}

throw new Exception(message);

}

catch (Exception Ex)

{

throw new Exception(Ex.Message);

}

catch (System.Net.WebException webex)

{

string message = webex.Message;

if (webex.Response != null)

{

if (webex.Response.ContentLength != 0)

{

using (Stream stream = webex.Response.GetResponseStream())

{

using (StreamReader reader = new StreamReader(stream))

{

message = reader.ReadToEnd();

}

}

}

}

throw new Exception(message);

}

catch (Exception Ex)

{

throw new Exception(Ex.Message);

}

Please feel free to contact us in case you have further comments or questions.

Best Regards,