Being surfing for last 3-4 days downloading, running and fixing issues with available demo projects online, none of them work so far.
I need to upload an image using WCF webservice. Where from client side end I like to upload it by means of form (multipart/form-data), including some file description.
Any solution working with proper answer? My mind is really stacked overflow trying different solution. One which I initially have I am able to upload a text file where file gets created with some extra content in it. I need to upload image file.
------------cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5
Content-Disposition: form-data; name=\"Filename\"
testing file gets upload...
When I upload image file, the image file is empty.
Initial Code (one implantation), method by means of which I get the .txt file as above, in case of image its blank (or say corrupt don't know)
private string uplaodFile(Stream stream)
{
StreamReader sr = new StreamReader(stream);
int length = sr.ReadToEnd().Length;
byte[] buffer = new byte[length];
stream.Read(buffer, 0, length);
FileStream f = new FileStream(Path.Combine(HostingEnvironment.MapPath("~/Upload"), "test.png"), FileMode.OpenOrCreate);
f.Write(buffer, 0, buffer.Length);
f.Close();
stream.Close();
return "Recieved the image on server";
}
another;
public Stream FileUpload(string fileName, Stream stream)
{
string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Upload"), fileName);
int length = 0;
using (FileStream writer = new FileStream(FilePath, FileMode.Create))
{
int readCount;
var buffer = new byte[8192];
while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, readCount);
length += readCount;
}
}
return returnJson(new { resp_code = 302, resp_message = "occurred." });
}
Related
Why am I getting this error? I'm trying to extract information from a bank statement PDF and tally different bills for the month. I write the data from a PDF to a text file so I can get specific data from the file (e.g. ASPEN HOME IMPRO, then iterate down to what the dollar amount is, then read that text line to a string)
When the Files.readAllLines(Path.get("bankData").get(0) code is run, I get the error. Any thoughts why? Encoding issue?
Here is the code:
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\wmsai\\Desktop\\BankStatement.pdf");
PDFTextStripper stripper = new PDFTextStripper();
BufferedWriter bw = new BufferedWriter(new FileWriter("bankData"));
BufferedReader br = new BufferedReader(new FileReader("bankData"));
String pdfText = stripper.getText(Loader.loadPDF(file)).toUpperCase();
bw.write(pdfText);
bw.flush();
bw.close();
LineNumberReader lineNum = new LineNumberReader(new FileReader("bankData"));
String aspenHomeImpro = "PAYMENT: ACH: ASPEN HOME IMPRO";
String line;
while ((line = lineNum.readLine()) != null) {
if (line.contains(aspenHomeImpro)) {
int lineNumber = lineNum.getLineNumber();
int newLineNumber = lineNumber + 4;
String aspenData = Files.readAllLines(Paths.get("bankData")).get(0); //This is the code with the error
System.out.println(newLineNumber);
break;
} else if (!line.contains(aspenHomeImpro)) {
continue;
}
}
}
So I figured it out. I had to check the properties of the text file in question (I'm using Eclipse) to figure out what the actual encoding of the text file was.
Then, when creating the file in the program, encode the text file to UTF-8 so that Files.readAllLines could read and grab the data I wanted to get.
I'm trying to write a powershell script that will loop through a csv file looking for Tiff & PDF files using ItextSharp dll. The desired end result is every image and page of a pdf needs to be in one large pdf.
My thoughts are to create two functions to accomplish this. 1 for images and the other for PDF's. The image function is working properly, but the pdf is throwing a error: Exception calling ".ctor" with "1" argument(s): " not found as file or resource."
Any thoughts on fixing add-pdf function?
Current script is below.
[System.Reflection.Assembly]::LoadFrom("C:\Temp\itextsharp`enter code here`\itextsharp.dll")
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$doc = New-Object itextsharp.text.document
#output PDF with all combined tiff and pdfs
$stream = [IO.File]::OpenWrite("C:\temp\itext\test.pdf")
$writer = [itextsharp.text.pdf.PdfWriter]::GetInstance($doc, $stream)
#$pdfCopy =New-Object iTextSharp.text.pdf.PdfCopy($doc, $stream)
$doc.Open()
$doc.SetMargins(0, 0, 0, 0)
#get the size of image and change pdf
function add-picture( $file2use){
$pic = New-Object System.Drawing.Bitmap($file2use )
$rect = New-Object iTextSharp.text.Rectangle($pic.Width, $pic.Height)
## Set the next page size to those dimensions and add a new page
$doc.SetPageSize( $rect )
$doc.NewPage()
#add image jpg
$img = [iTextSharp.text.Image]::GetInstance($file2use )
$doc.Add($img);
$pic.dispose()
}
function add-pdf( $newPDF){
$pdf2Merge = [System.IO.Path]::Combine("",$newPDF)
$pdfCopy = New-Object iTextSharp.text.pdf.PdfCopy($doc, $stream);
$reader = New-Object iTextSharp.text.pdf.PdfReader($pdf2Merge);
$pageCount = $reader.NumberOfPages;
for ($i = 1; $i -lt $pageCount ; $i++) {
$pdfCopy.AddPage(
$pdfCopy.GetImportedPage($reader, $i ))
# ^^^^^
# your page number here
}
#$pdfCopy.FreeReader($reader);
}
add-picture -file2use "C:\Temp\itext\3-26-04 (1).JPG"
add-picture -file2use "C:\Temp\itext\CCITT_1.TIF"
add-picture -file2use "C:\Temp\itext\CCITT_2.TIF"
add-pdf -file2use "C:\Temp\itext\test2.pdf"
## Cleanup
#$doc.Close()
$stream.Close()
I'm not too good within PowerShell but it looks like you are so you should be able to adapt this C# code very easily. The code in this post is adapted from some code I wrote earlier here.
First off, I really don't recommend keeping global iText abstraction objects around and binding various things to them over and over, that's just looking for trouble.
Instead, for images I'd recommend a simple function that takes a supplied image file and returns a byte array representing that image added to a PDF. Instead of a byte array you could also write the PDF to a temporary file and return that path instead.
private static byte[] ImageToPdf(string imagePath) {
//Get the size of the current image
iTextSharp.text.Rectangle pageSize = null;
using (var srcImage = new Bitmap(imagePath)) {
pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
}
//Simple image to PDF
using (var m = new MemoryStream()) {
using (var d = new Document(pageSize, 0, 0, 0, 0)) {
using (var w = PdfWriter.GetInstance(d, m)) {
d.Open();
d.Add(iTextSharp.text.Image.GetInstance(imagePath));
d.Close();
}
}
//Grab the bytes before closing out the stream
return m.ToArray();
}
}
Then just create a new Document and bind a PdfSmartCopy object to it. You can then enumerate your files, if you have an image, convert it to a PDF first, then just use the PdfSmartCopy method AddDocument() to add that entire document to the final output.
The code below just loop through a single folder, grabs images first and then PDFs but you should be able to adapt it pretty easily, hopefully.
//Folder that contains our sample files
var sourceFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "MergeTest");
//Final file that we're going to emit
var finalFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Create our final file, standard iText setup here
using (var fs = new FileStream(finalFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
//Use a smart object copies to merge things
using (var copy = new PdfSmartCopy(doc, fs)) {
//Open the document for writing
doc.Open();
//Loop through each image in our test folder
foreach (var img in System.IO.Directory.EnumerateFiles(sourceFolder, "*.jpg")) {
//Convert the image to a byte array
var imageAsPdf = ImageToPdf(img);
//Bind a reader to that PDF
using( var r = new PdfReader(imageAsPdf) ){
//Add that entire document to our final PDF
copy.AddDocument(r);
}
}
//Loop through each PDF in our test folder
foreach (var pdf in System.IO.Directory.EnumerateFiles(sourceFolder, "*.pdf")) {
//Bind a reader to that PDF
using (var r = new PdfReader(pdf)) {
//Add that entire document to our final PDF
copy.AddDocument(r);
}
}
doc.Open();
}
}
}
I am trying to use the iText library with c# to capture the text portion of pdf files.
I created a pdf from excel 2013 (exported) and then copied the sample from the web of how to use itext (added the lib ref to the project).
It reads perfectly the first page but it gets garbled info after that. It is keeping part of the first page and merging the info with the next page. The commented lines is when I was trying to solve the problem, the string "thePage" is recreated inside the for loop.
Here is the code. I can email the pdf to whoever can help with this issue.
Thanks in advance
public static string ExtractTextFromPdf(string path)
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
//string[] theLines;
//theLines = new string[COLUMNS];
//string thePage;
for (int i = 1; i <= reader.NumberOfPages; i++)
{
string thePage = "";
thePage = PdfTextExtractor.GetTextFromPage(reader, i, its);
string [] theLines = thePage.Split('\n');
foreach (var theLine in theLines)
{
text.AppendLine(theLine);
}
// text.AppendLine(" ");
// Array.Clear(theLines, 0, theLines.Length);
// thePage = "";
}
return text.ToString();
}
}
A strategy object collects text data and does not know if a new page has started or not.
Thus, use a new strategy object for each page.
I want to replace a particular text in PDF document. I am currently using itextSharp library to play with PDF documents.
I had extracted the bytes from pdfdocument and then replaced that byte and then write the document again with the bytes but it is not working. In the below example I am trying to replace string 1234 with 5678
Any advise on how to perform this would be helpful.
PdfReader reader = new PdfReader(opf.FileNames[i]);
byte[] pdfbytes = reader.GetPageContent(1);
PdfString oldstring = new PdfString("1234");
PdfString newstring = new PdfString("5678");
byte[] byte1022 = oldstring.GetOriginalBytes();
byte[] byte1067 = newstring.GetOriginalBytes();
int position = 0;
for (int j = 0; j <pdfbytes.Length ; j++)
{
if (pdfbytes[j] == byte1022[0])
{
if (pdfbytes[j+1] == byte1022[1])
{
if (pdfbytes[j+2] == byte1022[2])
{
if (pdfbytes[j+3] == byte1022[3])
{
position = j;
break;
}
}
}
}
}
pdfbytes[position] = byte1067[0];
pdfbytes[position + 1] = byte1067[1];
pdfbytes[position + 2] = byte1067[2];
pdfbytes[position + 3] = byte1067[3];
File.WriteAllBytes(opf.FileNames[i].Replace(".pdf","j.pdf"), pdfbytes);
What makes you think 1234 is part of the page's content stream and not of a form XObject? Your code is never going to work in general if you don't parse all the resources of a page.
Also: I see GetPageContent(), but I don't see you using SetPageContent() anywhere. How are the changes ever going to be stored in the PdfReader object?
Moreover, I don't see you using PdfStamper to write the altered PdfReader contents to a file.
Finally: I'm to shy to quote the words of Leonard Rosenthol, Adobe's PDF Architect, but ask him, and he'll tell you personally that you shouldn't do what you're trying to do. PDF is NOT a format for editing.Read the intro of chapter 6 of the book I wrote on iText: http://www.manning.com/lowagie2/samplechapter6.pdf
I want to download a file and save it into my app folder. I have to download different files with different formats, but only one each time.
I've read that I have to use HttpUtils, but sample codes are to difficult for me (I'm too noob).
Can anyone upload any sample code?? Thanks!!
This should point you in the right direction:
URL u = new URL(urlString);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File file = new File(outputDirectoryFile, outputFileName);
OutputStream out = new FileOutputStream(file);
InputStream in = c.getInputStream();
byte[] buffer = new byte[4096];
while ( (int len1 = in.read(buffer)) > 0 ) {
out.write(buffer,0, len1);
}
in.close();
out.close();
c.disconnect();
Remember, you should never perform operations like this on the default UI tread. It could prompt the user to force close your app. Read more here:
http://developer.android.com/resources/articles/painless-threading.html
This is how I finally do:
imgurl = "http://dl.dropbox.com/u/25045/file.jpg"
HttpUtils.CallbackActivity = "myactivity" 'Current activity name.
HttpUtils.CallbackJobDoneSub = "JobDone"
HttpUtils.Download("Job1", imgurl)
Dim out As OutputStream
out = File.OpenOutput(File.DirInternal, "file.jpg", True)
File.Copy2(HttpUtils.GetInputStream(imgurl), out)
out.Close