Hi Anand,
Hi Anand,
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,
Hi Anand,
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,
Hi,
Hi,
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,