How can I use Itext in PHP? - php

Itext is a powerful toolkit for PDF generation, PDF programming, handling & manipulation. Java sample:
public void processPDF(String src, String dest) {
try {
PdfReader reader = new PdfReader(src);
PdfArray refs = null;
PRIndirectReference reference = null;
int nPages = reader.getNumberOfPages();
for (int i = 1; i <= nPages; i++) {
PdfDictionary dict = reader.getPageN(i);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object.isArray()) {
refs = dict.getAsArray(PdfName.CONTENTS);
ArrayList<PdfObject> references = refs.getArrayList();
for (PdfObject r : references) {
reference = (PRIndirectReference) r;
PRStream stream = (PRStream) PdfReader.getPdfObject(reference);
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("test", "tested");
stream.setData(dd.getBytes());
}
}
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF-8");
System.out.println("content---->" + dd);
dd = dd.replaceAll("#pattern_1234", "trueValue");
dd = dd.replaceAll("This", "FIRST");
stream.setData(dd.getBytes(StandardCharsets.UTF_8));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
catch (Exception e) {
}
}
The question is how I can use this toolkit for PHP or there is any PHP toolkit like this?
I am using Yii2 Framework and just want to replace text inside a certain file (.doc, .docx, .pdf)
Original file:
Expected file after editing:

Related

how to convert java code to php?

I have this piece of code which is in java but i want it in php .
there is a function to convert hex to byte . and a main code:
public static byte[] ConvertHexStringToByteArray(String s)
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
and here is main code :
public static String hmacSha1(String value, String key)
{
try
{
// Get an hmac_sha1 key from the raw key bytes byte[]
keyBytes = ConvertHexStringToByteArray(key);
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing
key Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes(StandardCharsets.US_ASCII));
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
Hello
Your Java code in php is same as blow :
$key = strtolower($CPCode.$service_id.$price.$timestamp.$request_id);
$authKey = $CPCode;
$sign = hash_hmac("sha1",$key,$authKey);
Good Luck

Php gzcompress android decompress

I was trying to compress a String in php using the following code.
<?php
$compressed = gzcompress('Compress me', 9);
echo $uncompressed;
?>
The compressed string is "xÚsÎÏ-(J-.VÈM½?".
But when tried to decompress this in java using the following function
public static String unzipString(String zippedText) {
String unzipped = null;
try {
byte[] zbytes = zippedText.getBytes("ISO-8859-1");
// Add extra byte to array when Inflater is set to true
byte[] input = new byte[zbytes.length + 1];
System.arraycopy(zbytes, 0, input, 0, zbytes.length);
input[zbytes.length] = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(input);
InflaterInputStream in = new InflaterInputStream(bin);
ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
int b;
while ((b = in.read()) != -1) {
bout.write(b);
}
bout.close();
unzipped = bout.toString();
} catch (IOException io) {
printIoError(io);
}
return unzipped;
}
I was getting null string..Please correct me if i did something wrong this code.

Windowsphone to PHP communication through Webclient

I want to upload an Image i selected with the PhotoChooserTask.
The Selection itself works fine and i can open the Image.
I also already decoded it to Base64 (Works).
Since I can't find any working example on how to work with httpwebrequest on windowsphone I tried it the following way.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
MyImage.Source = bmp;
String str = BitmapToByte(MyImage);
String url = "http://klopper.puppis.uberspace.de/php/app/image.php?image="+ str;
LoadSiteContent(url);
}
}
The rest of the code is working fine.
I get: System.IO.FileNotFoundException
If I change the str to "test" it's working.
Is the problem, that the string is too long?
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("http://localhost:4223/File/Upload", UriKind.Absolute);
WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "POST");
}
Reference
to post image file in windows phone 7 application

need equivalent PHP (HttpWebRequest and Stream or curl) code for this .net code

i got a problem in PHP. i want to get all the bus stations in india. so i have made an xml request and post that xml data to given API URL. but i did not get the result. below is the .net code which is working fine. even i have used the "HttpRequest" method in php, but it gives me an error like "Fatal error: Class 'HttpRequest' not found".
can anybody help me to give me the equivalent code in php or possible ways to get the data..?
thanks in advance.
.net code (working fine)
protected void getBusServices(string journeydate)
{
XmlDocument doc = new XmlDocument();
StringReader stream;
StreamReader reader;
XmlTextReader textreader;
HttpWebRequest req;
HttpWebResponse response;
try
{
string password = "password";
DateTime dt = Convert.ToDateTime(journeydate);
string strJrneyDate = dt.ToString("MM-dd-yyyy");
string strRtDate = dt.AddDays(3).ToString("MM-dd-yyyy");
string url = Bus_Api_Url;
string RequestCommand = "<Command>GET_STATIONS</Command> <Username>username</Username> <Password>password</Password>";
req = (HttpWebRequest)WebRequest.Create(url);
string RequestData = "RequestXML=<?xml version='1.0' encoding='utf-8' ?><BusRequest xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + RequestCommand + "</BusRequest>";
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = RequestData.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
{
writer.Write(RequestData);
}
response = (HttpWebResponse)req.GetResponse();
Stream responsestream = response.GetResponseStream();
reader = new StreamReader(responsestream);
string xmlresponse = reader.ReadToEnd();
stream = new StringReader(xmlresponse);
textreader = new XmlTextReader(stream);
doc.LoadXml(xmlresponse);
DataSet ds = new DataSet();
ds.ReadXml(textreader);
}
catch (Exception ex)
{
EBUtils.Logger.LogError.Publish(ex);
}
finally
{
reader = null;
// stream = null;
reader = null;
response = null;
doc = null;
}
}
}
its really simple, check out http://php.net/manual/en/simplexml.examples-basic.php
i've used the same method lot of times, heres a little snippet from one of my active php projects.
$file = "http://the_address_of_the_xml_file.com";
if(!$xml = simplexml_load_file($file)) {
return 0;
} else { //open
$status = $xml->attributes()->statu
if($status=='ok') {//open
$bio = $xml->artist->bio;
//closed
for ($i = 0; $i < 1; $i++) {
and how about file_get_content ?
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
ha im not on top form today, in bed really unwell ;)

uploading image and php POST method in windows phone

this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/

Categories