How do I convert this into Win Forms with a button click? - program-entry-point

namespace iText.Samples.Sandbox.Tables
{
public class SimpleTable
{
public static readonly string DEST = "results/sandbox/tables/simple_table.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new SimpleTable().ManipulatePdf(DEST);
}
private void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Table table = new Table(UnitValue.CreatePercentArray(8)).UseAllAvailableWidth();
for (int i = 0; i < 16; i++)
{
table.AddCell("hi");
}
doc.Add(table);
doc.Close();
}
}
}
It my seem easy for most, but I have tried and tried and am just stumped. It is not just a console app, and it is not just a class. I am missing something simple I am sure but I am not trying to do a command line app either where I pass arguments to this app. Please help.
Tried all I could.
I have done plenty of forms apps and a few console apps, but I know I am missing something very simple.
I have looked and don't see my answer.

Copy the whole class into your project.
Change the Main method name to something else.
You could remove the parameter of the Main method.
Call SimpleTable.methodName() in the ButtonClick method.
That should do it.

Related

How to set interactive PDF form in read-only mode while writing as new PDF by using Apache PDFBox?

I am using Apache PDFBox library to fill information in fillable PDF form(AcroFrom). After complete information filling, I needs to write as a new PDF file (in non-editable format).
I tried setReadOnly() method, which is available in AccessPermission class. But still I can able to edit the values in new created PDF document.
Code:
private static PDDocument _pdfDocument;
public static void main(String[] args) {
String originalPdf = "C:/sample/Original.pdf";
String targetPdf = "C:/sample/target.pdf";
try {
populateAndCopy(originalPdf, targetPdf);
-----------
-----------
-----------
-----------
}
} // Main method complted
private static void populateAndCopy(String originalPdf, String targetPdf) throws IOException, COSVisitorException {
_pdfDocument = PDDocument.load(originalPdf);
_pdfDocument.getNumberOfPages();
_pdfDocument.getCurrentAccessPermission().setCanModify(false);
_pdfDocument.getCurrentAccessPermission().setReadOnly();
System.out.println(_pdfDocument.getCurrentAccessPermission().isReadOnly());
_pdfDocument.save(targetPdf);
_pdfDocument.close();
}
Please help me to fix this issue.
Your code does not set any encryption, that is the problem.
Try this:
AccessPermission ap = new AccessPermission();
ap.setCanModify(false);
ap.setReadOnly();
StandardProtectionPolicy spp = new StandardProtectionPolicy("owner-password", "", ap);
spp.setEncryptionKeyLength(128);
doc.protect(spp);
doc.save(targetPdf);
doc.close();
I've set 128 as the keylength as 256 is not supported in 1.8 and 40 is too short.
A user will be able to open the document without password (see the empty password parameter), but he'll have only the restricted rights.
public static void main(String[] args) {
try {
String formTemplate = "xyz.pdf";
// load the document
PDDocument pdfDocument = PDDocument.load(new File(formTemplate));
// get the document catalog
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
// as there might not be an AcroForm entry a null check is necessary
if (acroForm != null)
{
// Retrieve an individual field and set its value.
PDTextField field1 = (PDTextField) acroForm.getField( "_lastName" );
field1.setValue("pppp");
PDTextField field2 = (PDTextField) acroForm.getField( "_firstName" );
field2.setValue(aaaa");
}
// flatten() method saves the PDF read only
acroForm.flatten();
// Save and close the filled out form.
pdfDocument.save("xyz.pdf");
pdfDocument.close();
System.out.println("Done!!");
} catch(Exception e) {
e.printStackTrace();
}
}

get data from the server using WCF Windows phone 8

first the server code is working well
//declare the target list to be the reciver
List<string> list = new List<string>();
//at the first declare that
//then call it/
private void check(double l, double lo)
{
Service1Client client = new Service1Client();
client.pbackCompleted += new EventHandler<pbackCompletedEventArgs>(pResult);
client.pbackAsync(l, lo);
}
private void pResult(object sender, pbackCompletedEventArgs e)
{
list = e.Result.ToList<string>();
}
but in debugging list is still null ?
and the function pResult as it is not here ?
how can i return the list and assign it to my list on the device code?
thanks in advance
Try this directly, it worked for me
{
Service1Client client = new Service1Client();
client.pbackAsync(l, lo);
client.pbackCompleted += pResult;
}
void pResult(object sender, pbackCompletedEventArgs e)
{
list = e.Result.ToList<string>();
}
thanks for all, It works as i write in my problem, so there is no problem from the beginning.
May be its microsoft SDK.
#Hitesh Salian thanks a lot. thanks for your try, At real when it didn't work i tried your answer but didn't work.
then suddenly nothing change and the code worked.

Drag and drop image file from explorer to application

I'm trying to drag an image file from explorer into my wpf image control. My current code is
private void Image_Drop(object sender, DragEventArgs e)
{
string fpath = (string)e.Data.GetData(DataFormats.StringFormat);
BitmapImage tmpImage = new BitmapImage((new Uri(fpath)));
testImg.Source = tmpImage;
}
Which is currently giving me NullReferenceException error when I drop the file on the control.
Update:
Using Patrick's suggestion, by changing the code to this
private void Image_Drop(object sender, DragEventArgs e)
{
object data = e.Data.GetData(DataFormats.FileDrop);
foreach (string str in (string[])data)
{
BitmapImage tmpImage = new BitmapImage((new Uri(str)));
testImg.Source = tmpImage;
}
}
The image correctly update the source. Will probably need to add code for handling multiple images selection drop.
You should use the DataFormats.FileDrop. It will give a list of file names in the GetData. This is a working example from my own app:
object data = e.Data.GetData(DataFormats.FileDrop);
if (data is string[])
{
string[] files = (string[])data;
}
You are trying to get a file as a string, so I imagine it's your e.Data.GetData(DataFormats.StringFormat) line that is throwing. If you're dropping a bitmap onto your control then you can treat it as such. Try this.
private void Image_Drop(object sender, DragEventArgs e)
{
BitmapImage tmpImage = e.Data.GetData(DataFormats.Bitmap);
testImg.Source = tmpImage;
}
Although I recommend you put in code to ensure you are checking the type of what has been dragged onto your control before assuming it is a bitmap.

Wicket : FileUploadPage doesnt refresh the filepath

again, i got a problem with wicket. Im trying to upload data with my Class "FileUploadPanel", which is implemented on another Page "Class A":
Class A
...
/* uploadfields for Picture and Video */
ArrayList<String> picExt = new ArrayList<String>();
ArrayList<String> videoExt = new ArrayList<String>();
picExt.add("jpg");
videoExt.add("mp4");
final FileUploadPanel picUpload = new FileUploadPanel("picUpload", "C:\\", picExt);
final FileUploadPanel videoUpload = new FileUploadPanel("videoUpload", "C:\\", videoExt);
final Form form = new Form("form"){
protected void onSubmit() {
...
// Save the path of Video and Picture into Database
table.setVideo(videoUpload.getFilepath());
table.setPicture(picUpload.getFilepath());
...
}
...
Class FileUploadPanel
public class FileUploadPanel extends Panel {
private static final long serialVersionUID = -2059476447949908649L;
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "C:\\";
private String filepath = "";
private List<String> fileExtensions;
/**
* Constructor of this Class
* #param id the wicket-id
* #param uploadFolder the folder, in which the File will be uploaded
* #param fileExtensions List of Strings
*/
public FileUploadPanel(String id, String uploadFolder, List<String> fileExtensions) {
super(id);
this.UPLOAD_FOLDER = uploadFolder;
this.fileExtensions = fileExtensions;
add(fileUpload = new FileUploadField("fileUpload"));
}
#Override
public void onComponentTag(ComponentTag tag){
// If no file is selected on startup
if(fileUpload.getFileUpload() == null){
return;
}
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file,
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
filepath = UPLOAD_FOLDER + uploadedFile.getClientFileName();
// if file in upload-folder already exists -> delete it
if (newFile.exists()) {
newFile.delete();
}
try {
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
} catch (Exception e) {
throw new IllegalStateException("Error");
}
}
}
public String getFilepath() {
return filepath;
}
}
Well, if i use the submit-Button on my "Class A", the Pic and Video get saved on C:\, which is quite good so far. I thought i finally get along with wicket, but i cheered too soon...
Problem: The correct path is not saved in the Database, which is handled in the Form of "Class A"
I really dont get it, because the onComponentTag(...) of my FileUploadPanel must be executed when using the submit-button. Thats because i added some validations like "picture must be a JPG or wont be saved" in onComponentTag(...) - and that worked. So im sure, the onComponentTag(...) is executed when the Submit-Button of the Form is used, which also means the filepath should be up-to-date.
What is it im doin wrong this time?
Thank in Advance!
Greeting
V1nc3nt
You are using
File newFile = new File(UPLOAD_FOLDER +
uploadedFile.getClientFileName());
this code to create a new File.
Instead of it you can try this one :
File file = new File(UPLOAD_FOLDER ,
uploadedFile.getClientFileName());
And then get the absolute path and save it:
newFile.getAbsolutePath();

How does one save the .MoreInfo property of a PDF with iTextSharp?

I currently have the following class that I'm trying to add a Hashtable of metadata properties to a PDF. The problem is, even though it appears to assign the hashtable to the stamper.MoreInfo property it doesn't appear to save the MoreInfo property once the stamper is closed.
public class PdfEnricher
{
readonly IFileSystem fileSystem;
public PdfEnricher(IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void Enrich(string pdfFile, Hashtable fields)
{
if (!fileSystem.FileExists(pdfFile)) return;
var newFile = GetNewFileName(pdfFile);
var stamper = GetStamper(pdfFile, newFile);
SetFieldsAndClose(stamper, fields);
}
string GetNewFileName(string pdfFile)
{
return fileSystem.GetDirectoryName(pdfFile) + #"\NewFileName.pdf";
}
static void SetFieldsAndClose(PdfStamper stamper, Hashtable fields)
{
stamper.MoreInfo = fields;
stamper.FormFlattening = true;
stamper.Close();
}
static PdfStamper GetStamper(string pdfFile, string newFile)
{
var reader = new PdfReader(pdfFile);
return new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
}
}
Any ideas?
As always, Use The Source.
In this case, I saw a possibility fairly quickly (Java source btw):
public void close() throws DocumentException, IOException {
if (!hasSignature) {
stamper.close( moreInfo );
return;
}
Does this form already have signatures of some sort? Lets see when hasSignatures would be true.
That can't be the case with your source. hasSignatures is only set when you sign a PDF via PdfStamper.createSignature(...), so that's clearly not it.
Err... how are you checking that your MoreInfo was added? It won't be in the XMP metadata. MoreInfo is added directly to the Doc Info dictionary. You see them in the "Custom" tab of Acrobat (and most likely Reader, though I don't have it handy at the moment).
Are you absolutely sure MoreInfo isn't null, and all its values aren't null?
The Dictionary is just passed around by reference, so any changes (in another thread) would be reflected in the PDF as it was written.
The correct way to iterate through a document's "Doc info dictionary":
PdfReader reader = new PdfReader(somePath);
Map<String, String> info = reader.getInfo();
for (String key : info.keySet()) {
System.out.println( key + ": " + info.get(key) );
}
Note that this will go through all the fields in the document info dictionary, not just the custom ones. Also be aware that changes made the the Map from getInfo() will not carry over to the PDF. The map is new'ed, populated, and returned.