Generating PDF files with PHP and FPDF

October 12, 2009

PHP allows you to generate PDF files dynamically, which can be useful for a variety of tasks. FPDF is a free PHP class containing a number of functions that let you create and manipulate PDFs.

PDFlib

The PHP API contains a number of functions for handling PDF files designed to be used with the PDFlib. Although extensive, this library is not free for commercial use. A free version called PDFlib Lite is available for personal use, but is limited in functionality. To use the full PDFlib library you must purchase a rather expensive license.

Why FPDF?

An alternative way of generating PDF files with PHP is using FPDF, a free PHP class containing a number of functions for creating and manipulating PDFs. The key word here is free. You are free to download and use this class or customise it to fit your needs. In addition to being free, it’s also simpler to use than PDFlib. The PDFlib needs to be installed as an extension in your PHP package, whereas FPDF can just be included in your PHP script and it’s ready to use.

Creating PDF files

To get started, you will need to download the FPDF class from the FPDF Web site and include it in your PHP script like this:

require(‘fpdf.php’);

Below is an example of how you can generate a simple PDF using FPDF.

We begin by creating a new FPDF object with:

$pdf= new FPDF();

The FPDF constructor can take the following parameters:

|>String orientation (P or L) — portrait or landscape
|>String unit (pt,mm,cm and in) — measure unit
|>Mixed format (A3, A4, A5, Letter and Legal) — format of pages

Next, we are going to set some document properties:

$pdf->SetAuthor(‘Lana Kovacevic’);
$pdf->SetTitle(‘FPDF tutorial’);

Because we want to use the same font throughout the whole document, we can set it before we create a page.

$pdf->SetFont(‘Helvetica’,'B’,20);
$pdf->SetTextColor(50,60,100);

The SetFont function takes three parameters; the font family, style and size. We are using Helvetica, Bold and 20 points, which will be applied to the title of our document. You can either use one of the regular font families or set up a different one using the AddFont () function.

With SetTextColor () we are also setting the font colour for the entire document. The colours can be represented as RGB or grey scale. Here we are using RGB values.

Now that that’s done, let’s set up a page for our PDF document.

$pdf->AddPage(‘P’);
$pdf->SetDisplayMode(real,’default’);

You can pass the AddPage () a parameter of “P” or “L” to specify the page orientation. I’ve used “P” for portrait. The SetDisplayMode function determines how the page will be displayed. You can pass it zoom and layout parameters. Here we’re using 100 percent zoom and the viewer’s default layout.

Now, that we’ve set up a page, let’s insert an image to make it look nicer and make it a link while we’re at it. We’ll display the FPDF logo by calling the Image function and passing it the following parameters — name of the file, the dimensions and the URL.

$pdf->Image(‘logo.png’,10,20,33,0,’ ‘,’http://www.fpdf.org/’);

You could have also inserted the link with:

$pdf->Link(10, 20, 33,33, ‘http://www.fpdf.org/’);

Now let’s make a title for our document with a border around it.

$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,’FPDF Tutorial’,1,0,’C',0);

The SetXY function sets the position of x and y coordinates, where we want the title to appear. SetDrawColor will set the colour of the border, using RGB values. After that’s done, we call the Cell function to print out a cell rectangle along with the text of our title. We are passing the function the following parameters; width, height, text, border, ln, align and fill. The border is either 0 for no border or 1 for frame. For ln we are using the default value 0, “C” to centre align the text inside it and 0 for fill. Had we used 1 for fill the rectangle would have been coloured in. With a value of 0 we are making it transparent.

Now we want to write the main text to the PDF, that is display a little message.

$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,’Congratulations! You have generated a PDF. ‘);

Again we are setting the x and y positions of the text, but this time we are reducing the font size with the SetFontSize function. The write function will print the text to a PDF. The parameter 5 will set the line height. This is only relevant however, if there are multiple lines of text.

Finally we want to send the output to a given destination, using the Output function.

$pdf->Output(‘example1.pdf’,'I’);

Here we are passing the function the name of the file and the destination, in this case “I”. The “I” parameter will send the output to the browser.

Putting it all together:

SetAuthor(‘Lana Kovacevic’);
$pdf->SetTitle(‘FPDF tutorial’);

//set font for the entire document
$pdf->SetFont(‘Helvetica’,'B’,20);
$pdf->SetTextColor(50,60,100);

//set up a page
$pdf->AddPage(‘P’);
$pdf->SetDisplayMode(real,’default’);

//insert an image and make it a link
$pdf->Image(‘logo.png’,10,20,33,0,’ ‘,’http://www.fpdf.org/’);

//display the title with a border around it
$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,’FPDF Tutorial’,1,0,’C',0);

//Set x and y position for the main text, reduce font size and write content
$pdf->SetXY (10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,’Congratulations! You have generated a PDF.’);

//Output the document
$pdf->Output(‘example1.pdf’,'I’);
?>

Now that you’ve learnt how to generate a simple PDF, let’s see what else we can do with FPDF. The example code below demonstrates how to make a header and a footer for your document.

Image(‘logo.png’,10,8,33);
$this->SetFont(‘Helvetica’,'B’,15);
$this->SetXY(50, 10);
$this->Cell(0,10,’This is a header’,1,0,’C');
}

function Footer()
{
$this->SetXY(100,-15);
$this->SetFont(‘Helvetica’,'I’,10);
$this->Write (5, ‘This is a footer’);
}
}

$pdf=new PDF();
$pdf->AddPage();
$pdf->Output(‘example2.pdf’,'D’);
?>

As you can see we are creating a child class of FPDF using inheritance and setting up the behaviour for both the Header and Footer functions. We then create a new object of this PDF class and add a page to our document. The AddPage () will automatically call the Header and Footer. Finally, we output it to a file called example2.pdf, this time using the “D” option for the sake of the example. This will send the file to the browser and open a dialog box, prompting the user to save the file.

Now that you have an understanding of how FPDF works, go ahead and play with some of its functions and have fun building your own PDFs. For the full list of functions, refer to the FPDF Web site.

Is Smarty right for me?

October 12, 2009

Although Smarty is known as a “Template Engine”, it would be more accurately described as a “Template/Presentation Framework.” That is, it provides the programmer and template designer with a wealth of tools to automate tasks commonly dealt with at the presentation layer of an application. I stress the word Framework because Smarty is not a simple tag-replacing template engine. Although it can be used for such a simple purpose, its focus is on quick and painless development and deployment of your application, while maintaining high-performance, scalability, security and future growth.

Here are some of the more notable features of Smarty:

Caching: Smarty provides fine-grained caching features for caching all or parts of a rendered web page, or leaving parts uncached. Programmers can register template functions as cacheable or non-cachable, group cached pages into logical units for easier management, etc.

Configuration Files: Smarty can assign variables pulled from configuration files. Template designers can maintain values common to several templates in one location without intervention from the programmer, and config variables can easily be shared between the programming and presentation portions of the application.

Security: Templates do not contain PHP code. Therefore, a template designer is not unleashed with the full power of PHP, but only the subset of functionality made available to them from the programmer (application code.)

Easy to Use and Maintain: Web page designers are not dealing with PHP code syntax, but instead an easy-to-use templating syntax not much different than plain HTML. The templates are a very close representation of the final output, dramatically shortening the design cycle.

Variable Modifiers: The content of assigned variables can easily be adjusted at display-time with modifiers, such as displaying in all upper-case, html-escaped, formatting dates, truncating text blocks, adding spaces between characters, etc. Again, this is accomplished with no intervention from the programmer.

Template Functions: Many functions are available to the template designer to handle tasks such as generating HTML code segments (dropdowns, tables, pop-ups, etc.), displaying content from other templates in-line, looping over arrays of content, formatting text for e-mail output, cycling though colors, etc.

Filters: The programmer has complete control of template output and compiled template content with pre-filters, post-filters and output-filters.

Resources: Templates can be pulled from any number of sources by creating new resource handlers, then using them in the templates.

Plugins: Almost every aspect of Smarty is controlled through the use of plugins. They are generally as easy as dropping them into the plugin directory and then mentioning them in the template or using them in the application code. Many user-community contributions are also available. (See the plugins section of the forum and wiki.)

Add-ons: Many user-community contributed Add-ons are available such as Pagination, Form Validation, Drop Down Menus, Calendar Date Pickers, etc. These tools help speed up the development cycle, there is no need to re-invent the wheel or debug code that is already stable and ready for deployment. (see the Add-ons section of the forum and wiki.)

Debugging: Smarty comes with a built-in debugging console so the template designer can see all of the assigned variables and the programmer can investigate template rendering speeds.

Compiling: Smarty compiles templates into PHP code behind the scenes, eliminating run-time parsing of templates.

Performance: Smarty performs extremely well, despite its vast feature set. Most of Smarty’s capabilities lie in plugins that are loaded on-demand. Smarty comes with numerous presentation tools, minimizing your application code and resulting in quicker, less error-prone application development/deployment. Smarty templates get compiled to PHP files internally (once), eliminating costly template file scans and leveraging the speed of PHP op-code accelerators.

So is Smarty right for you? What it comes down to is using the right tool for the job. If you want simple variable replacement, you might want to look at something simpler or even roll your own. If you want a robust templating framework with numerous tools to assist you as your application evolves into the future, Smarty is likely a good choice.

Convert Text to Uppercase

October 12, 2009

Converting a text string to uppercase is very easy using the JavaScript toUpperCase() method.

This script takes the input from the first text field and outputs it to the second. You can adapt the script to accept and output the string in other ways.

Place the following code in the document head:

function makeUppercase() {
document.form1.outstring.value = document.form1.instring.value.toUpperCase();
}

Place the following code in the document body. This includes two text fields (one for the input and one for the resulting output) and a button to initiate the conversion:

>” onClick=”makeUppercase();”>

20 Top jQuery tips & tricks for jQuery programmers

October 12, 2009

Following are few very useful jQuery Tips and Tricks for all jQuery developers.
1. Optimize performance of complex selectors

Query a subset of the DOM when using complex selectors drastically improves performance:
1.var subset = $(“”);
2.$(“input[value^='']“, subset);
2. Set Context and improve the performance

On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.
1.$(“input:radio”, document.forms[0]);
3. Live Event Handlers

Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:
1.$(‘button.someClass’).live(‘click’, someFunction);

This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.

Likewise, to stop the live event handling:
1.$(‘button.someClass’).die(‘click’, someFunction);

These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases. Live event will work starting from jQuery 1.3
4. Checking the Index

jQuery has .index but it is a pain to use as you need the list of elements and pass in the element you want the index of
1.var index = e.g $(‘#ul>li’).index( liDomObject );

The following is easier:

if you want to know the index of an element within a set, e.g. list items within a unordered list:
1.$(“ul > li”).click(function ()
2.{
3. var index = $(this).prevAll().length;
4.});
5. Use jQuery data method

jQuery’s data() method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.
6. Fadeout Slideup effect to remove an element

Combine more than one effects in jQuery to animate and remove an element from DOM.
1.$(“#myButton”).click(function() {
2. $(“#myDiv”).fadeTo(“slow”, 0.01, function(){ //fade
3. $(this).slideUp(“slow”, function() { //slide up
4. $(this).remove(); //then remove from the DOM
5. });
6. });
7.});
7. Checking if an element exists

Use following snippet to check whether an element exists or not.
1.if ($(“#someDiv”).length) {
2. //hooray!!! it exists…
3.}
8. Add dynamically created elements into the DOM

Use following code snippet to create a DIV dynamically and add it into the DOM.
1.var newDiv = $(‘

‘);
2.newDiv.attr(“id”,”myNewDiv”).appendTo(“body”);
9. Line breaks and chainability

Instead of doing:
1.$(“a”).hide().addClass().fadeIn().hide();

You can increase readability like so:
1.$(“a”)
2. .hide()
3. .addClass()
4. .fadeIn()
5. .hide();
10. Creating custom selectors
01.$.extend($.expr[':'], {
02. over100pixels: function(a) {
03. return $(a).height() > 100;
04. }
05.});
06.
07.$(‘.box:over100pixels’).click(function() {
08. alert(‘The element you clicked is over 100 pixels high’);
09.});
11. Cloning an object in jQuery

Use .clone() method of jQuery to clone any DOM object in JavaScript.
1.// Clone the DIV
2.var cloned = $(‘#somediv’).clone();

jQuery’s clone() method does not clone a JavaScript object. To clone JavaScript object, use following code.
1.// Shallow copy
2.var newObject = jQuery.extend({}, oldObject);
3.
4.// Deep copy
5.var newObject = jQuery.extend(true, {}, oldObject);
12. Test if something is hidden using jQuery

We use .hide(), .show() methods in jquery to change the visibility of an element. Use following code to check the whether an element is visible or not.
1.if($(element).is(“:visible”) == “true”) {
2. //The element is Visible
3.}
13. Alternate way of Document Ready
1.//Instead of
2.$(document).ready(function() {
3. //document ready
4.});
5.//Use
6.$(function(){
7. //document ready
8.});
14. Selecting an element with . (period) in its ID

Use backslash in the selector to select the element having period in its ID.
1.$(“#Address\\.Street”).text(“Enter this field”);
15. Counting immediate child elements

If you want to count all the DIVs present in the element #foo
01.

02.

03.

04.
05.

06.
07.

08.
09.//jQuery code to count child elements
10.$(“#foo > div”).size()
16. Make an element to “FLASH”
1.jQuery.fn.flash = function( color, duration )
2.{
3. var current = this.css( ‘color’ );
4. this.animate( { color: ‘rgb(‘ + color + ‘)’ }, duration / 2 );
5. this.animate( { color: current }, duration / 2 );
6.}
7.//Then use the above function as:
8.$( ‘#importantElement’ ).flash( ’255,0,0′, 1000 );
17. Center an element on the Screen
01.jQuery.fn.center = function () {
02. this.css(“position”,”absolute”);
03. this.css(“top”, ( $(window).height() – this.height() ) / 2+$(window).scrollTop() + “px”);
04. this.css(“left”, ( $(window).width() – this.width() ) / 2+$(window).scrollLeft() + “px”);
05. return this;
06.}
07.
08.//Use the above function as:
09.$(element).center();
18. Getting Parent DIV using closest

If you want to find the wrapping DIV element (regardless of the ID on that DIV) then you’ll want this jQuery selector:
1.$(“#searchBox”).closest(“div”);
19. Disable right-click contextual menu

There’s many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:
1.$(document).ready(function(){
2. $(document).bind(“contextmenu”,function(e){
3. return false;
4. });
5.});
20. Get mouse cursor x and y axis

This script will display the x and y value – the coordinate of the mouse pointer.
1.$().mousemove(function(e){
2. //display the x and y axis values inside the P element
3. $(‘p’).html(“X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
4.});

Cron job in Code Igniter framework

October 12, 2009

Installation

1) Copy the code at the bottom of this code and save it in a file called cron.php anywhere on your server (but not in the document root!).

2) Set the CRON_CI_INDEX constant to the full absolute file/path of your CodeIgniter index.php file

3) Make this file directly executable:
chmod a+x cron.php
Usage

You can use this file to call any controller function:
./cron.php –run=/controller/method [--show-output] [--log-file=logfile] [--time-limit=N] [--server=http_server_name]
Command options
–run=/controller/method

(Required) The controller and method you want to run.
–show-output

(Optional) Display CodeIgniter’s output on the console (default: don’t display)
–log-file=logfile

(Optional) Log the date/time this was run, along with CodeIgniter’s output
–time-limit=N

(Optional) Stop running after N seconds (default=0, no time limit)
–server=http_server_name

(Optional) Set the $_SERVER[‘SERVER_NAME’] system variable (useful if your application needs to know what the server name is)
Troubleshooting

“I get this error when I try to execute ./cron.php:”
Invalid interpreter: /usr/bin/php^M

This is caused by not having UNIX-style line breaks, which usually happens by copying files created on other operating systems. Use this command to convert the line breaks to UNIX format:
mv cron.php cron.old
tr -d ‘\15\32′ cron.php
rm cron.old

cron.php bombs around line 111:
require(CRON_CI_INDEX); // Main CI index.php file[/cron]
This would only happen if you don‘t have the path to your application’s main [b]index.php[/b] defined correctly at line 24:
[/code]define(‘CRON_CI_INDEX’, ‘/var/www/vhosts/intranet/index.php’); // Your CodeIgniter main index.php file

“I don’t get any errors or output and the script doesn’t seem to run. What would cause this?”
Apparently some authentication libraries, such as Michael Wales’ Erkana authentication library, cause this sort of behaviour (it’s possible that any code that depends on sessions could cause this). Just use some conditional logic testing to see if the CRON constant is defined before auto-loading any authentication libraries.
The script
#!/usr/bin/php
FALSE);
foreach($argv as $arg)
{
list($param, $value) = explode(‘=’, $arg);
switch($param)
{
case ‘–run’:
// Simulate an HTTP request
$_SERVER['PATH_INFO'] = $value;
$_SERVER['REQUEST_URI'] = $value;
$required['--run'] = TRUE;
break;

case
‘-S’:
case ‘–show-output’:
define(‘CRON_FLUSH_BUFFERS’, TRUE);
break;

case
‘–log-file’:
if(is_writable($value)) define(‘CRON_LOG’, $value);
else die(“Logfile $value does not exist or is not writable!\n\n”);
break;

case
‘–time-limit’:
define(‘CRON_TIME_LIMIT’, $value);
break;

case
‘–server’:
$_SERVER['SERVER_NAME'] = $value;
break;

default:
die(
$usage);
}
}

if(!defined(‘CRON_LOG’)) define(‘CRON_LOG’, ‘cron.log’);
if(!defined(‘CRON_TIME_LIMIT’)) define(‘CRON_TIME_LIMIT’, 0);

foreach(
$required as $arg => $present)
{
if(!$present) die($usage);
}

# Set run time limit
set_time_limit(CRON_TIME_LIMIT);

# Run CI and capture the output
ob_start();

chdir(dirname(CRON_CI_INDEX));
require(CRON_CI_INDEX); // Main CI index.php file
$output = ob_get_contents();

if(
defined(‘CRON_FLUSH_BUFFERS’)) {
while(@ob_end_flush()); // display buffer contents
} else {
ob_end_clean();
}

# Log the results of this run
error_log(“### “.date(‘Y-m-d H:i:s’).” cron.php $cmdline\n”, 3, CRON_LOG);
error_log($output, 3, CRON_LOG);
error_log(“\n### \n\n”, 3, CRON_LOG);

echo
“\n\n”;

?>

Upload Via FTP – an alternative to move_uploaded_file

October 12, 2009

If you want to transfer files between SERVERS. NOTE : sometimes you wish to transfer files between two servers… or if you have built a CMS and you want ot install the program on a clients server, it is advisable to transfer files by FTP rather than the move_uplaoded_file. This function accepts a parameet — location of the file
<?php
function uploadFileFTP($FileName) {
//connect to the ftp server
$conn_id = ftp_connect(FTP_SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, FTP_USER, FTP_PASSWORD);

// check connection
if ((!$conn_id) || (!$login_result)) {
echo error=“FTP connection has failed!
Attempted to connect to “.FTP_SERVER.” for user : “.FTP_USER;
return false;
}

//skip these two steps if you dont want to change the working directory
ftp_chdir($conn_id, “wwwroot”);
ftp_chdir($conn_id, “my_folder”);

// upload the file
$upload = ftp_put($conn_id, $FileName, $source_file, FTP_BINARY);

if (!
$upload) {
echo error=“FTP upload has failed!”;
ftp_close($conn_id);
return false;
} else {
ftp_close($conn_id);
return $FileName;
}
}
?>

Java Source Code Obfuscator

October 8, 2009

The Java Obfuscator tool scrambles Java source code to make it very difficult to understand or reverse-engineer (example). This provides significant protection for source code intellectual property that must be shipped to a customer, and against the all-too-easy disassembly of Java class file object code. You only need to expose the public API that your classes offer to your customers; all your internal APIs and class names become inscrutable. It is a member of SD’s family of Source Code Obfuscators.
Java Obfuscator Features

* Replaces identifiers by nonsense names without affecting functionality
o User definable list of preserved names
o Predefined list of reserved names for Java JDK identifiers provided
* Strips comments and removes most source code structure
o User definable comment filtering, to preserve Copyright and public documentation
* No changes to the your Java compilation or execution procedures or environment
* Option to neatly format Java source code to aid development before obfuscation.
* Output encoding in ASCII, European ASCII, or UNICODE
* Command line and GUI interfaces

Example:
Java Sample Code before Obfuscation

(This is the same formatted code shown on the Java Formatter example page)

import javax.swing.JOptionPane;

public class Program1
{
public static void main(String args[]) {
String first,second;
double choice;
double radius,width,area,length;
String value = ” “; //intialize the string
value = JOptionPane.showInputDialog(“Please chose one of the options:”+”\n”+”a)Enter 1 to calculate the area of the Circle”+”\n”+”b)Enter 2 to calculate the area of the Triangle”+”\n”+”c)Enter 3 to calculate the area of the Square”+”\n”+”d)Enter 4 to calculate the area of the Rectangle”+”\n”+”e)Enter 5 to calculate the area of the Cube”+”\n”+”f)Enter 6 to exit the program”);
choice = Double.parseDouble(value);
while (choice != 6) {
//if(choice!=1||choice!=2||choice!=3||choice!=4||choice!=5)
// JOptionPane.showMessageDialog(null,”Wrong option entered”, ” error”,
// JOptionPane.ERROR_MESSAGE);
if (choice == 1) { //calculate the area of circle
first = JOptionPane.showInputDialog(“Enter the value of radius”);
radius = Double.parseDouble(first);
area = Math.PI*radius*radius;
//print out the result
JOptionPane.showMessageDialog(null,”The area of the Circle: “+area,”result”,JOptionPane.INFORMATION_MESSAGE);
} else
if (choice == 2) { //calculate the area of triangle
first = JOptionPane.showInputDialog(“Enter the value of lenght”);
second = JOptionPane.showInputDialog(“Enter the value of width”);
length = Double.parseDouble(first);
width = Double.parseDouble(second);
area = (width*length)/2;
JOptionPane.showMessageDialog(null,”The area of triangle: “+area,”result”,JOptionPane.INFORMATION_MESSAGE);
} else
if (choice == 3) { //calculate the area of square
first = JOptionPane.showInputDialog(“Enter the value of length”);
length = Double.parseDouble(first); //ge string into integer
area = length*length;
JOptionPane.showMessageDialog(null,”The area of the square: “+area,” result”,JOptionPane.INFORMATION_MESSAGE);
} else
if (choice == 4) { //calculate the area of rectangle
first = JOptionPane.showInputDialog(“Enter the value of length”);
second = JOptionPane.showInputDialog(“Enter the value of width”);
length = Double.parseDouble(first);
width = Double.parseDouble(second);
area = width*length;
JOptionPane.showMessageDialog(null,”The area of the rectangle: “+area,”result”,JOptionPane.INFORMATION_MESSAGE);
} else
if (choice == 5) { //calculat the area of cube
first = JOptionPane.showInputDialog(“Enter the value of length”);
length = Double.parseDouble(first);
area = 6*length;
JOptionPane.showMessageDialog(null,”The area of the cube: “+area,”result”,JOptionPane.INFORMATION_MESSAGE);
}
value = JOptionPane.showInputDialog(“Please chose one of the options:”+”\n”+”a)Enter 1 to calculate the area of the Circle”+”\n”+”b)Enter 2 to calculate the area of the Triangle”+”\n”+”c)Enter 3 to calculate the area of the Square”+”\n”+”d)Enter 4 to calculate the area of the Rectangle”+”\n”+”e)Enter 5 to calculate the area of the Cube”+”\n”+”f)Enter 6 to exit the program”);
choice = Double.parseDouble(value);
} //end of while loop
System.out.println(“Program terminated\n”);
System.exit(0);
} //end of main
}

Java Code after Obfuscation

Notice that comments are gone, names have been scrambled, text strings obscured. Larger constants (not shown here) have their radix twiddled. The obfuscator uses a special list provided by the user to define names that should be preserved, ensuring that public interfaces and accesses to public libraries remain valid. If you obfuscate a set of Java source files simultaneously, only the public symbols they collectively offer will be visible in the compiled source files.

import javax.swing.JOptionPane;

public class Program1
{
public static void main(String l1[]) {
String l10,O11;
double l100;
double O101,l110,l111,O1000;
String l1001 = ” “;
l1001 = JOptionPane.showInputDialog(“P\154\145\141se c\150o\163e40\157ne of the \157\160\164i\157ns:” + “12″ + “\14151\105\156t\145r40140\164o40\143alc\165late \164\150e40\141r\145a40of \164\150e40C\151\162c\154e” + “12″ + “b51Enter 2 t\15740c\141lc\165l\141\164e the \141\162\145a40o\146 t\150e40Tr\151\141n\147\154e” + “12″ + “c51Enter 340t\157 \143a\154\143ulate the ar\145\141 \157\14640th\145 \123quar\145″ + “12″ + “\144)\105\156\164\145r40440t\15740\143\141\154c\165\154a\164e40t\150e40ar\145a40o\146 \164h\145 R\145c\164a\156g\154e” + “12″ + “\145)\105\156\164\145r40540t\15740\143\141\154c\165\154a\164\14540\164h\145 \141\162ea40o\14640t\150e40Cub\145″ + “12″ + “\146)\105\156\164e\162 66 \164o \145xit the p\162\157gr\141m”);
l100 = Double.parseDouble(l1001);
while (l100 != 6) {
if (l100 == 1) {
l10 = JOptionPane.showInputDialog(“\105n\164\145\16240t\150e40v\141\154\165\14540o\14640r\141\144iu\163″);
O101 = Double.parseDouble(l10);
l111 = Math.PI * O101 * O101;
JOptionPane.showMessageDialog(null, “\124\150\14540\141r\145a40of40\164\150e Ci\162\143l\145724040 40″ + l111, “result”, JOptionPane.INFORMATION_MESSAGE);
} else
if (l100 == 2) {
l10 = JOptionPane.showInputDialog(“Ent\145r40\164\150e40v\141l\165e \157\14640\154en\147ht”);
O11 = JOptionPane.showInputDialog(“\105\156\164\145\162 \164h\145 value of40width”);
O1000 = Double.parseDouble(l10);
l110 = Double.parseDouble(O11);
l111 = (l110 * O1000) / 2;
JOptionPane.showMessageDialog(null, “T\150e area \157f40t\162i\141\156g\154e: ” + l111, “re\163ult”, JOptionPane.INFORMATION_MESSAGE);
} else
if (l100 == 3) {
l10 = JOptionPane.showInputDialog(“\105\156\164\145\162 \164h\145 value40of lengt\150″);
O1000 = Double.parseDouble(l10);
l111 = O1000 * O1000;
JOptionPane.showMessageDialog(null, “\124he area \157f \164h\145 \163\161uare: ” + l111, ” re\163ul\164″, JOptionPane.INFORMATION_MESSAGE);
} else
if (l100 == 4) {
l10 = JOptionPane.showInputDialog(“\105\156\164er t\150e40v\141lu\14540\157f len\147\164h”);
O11 = JOptionPane.showInputDialog(“E\156\164er the40v\141l\165e \157\146 width”);
O1000 = Double.parseDouble(l10);
l110 = Double.parseDouble(O11);
l111 = l110 * O1000;
JOptionPane.showMessageDialog(null, “T\150e are\14140o\146 \164h\145 rectangle: ” + l111, “\162\145\163\165\154t”, JOptionPane.INFORMATION_MESSAGE);
} else
if (l100 == 5) {
l10 = JOptionPane.showInputDialog(“E\156ter t\150\14540v\141l\165\14540of lengt\150″);
O1000 = Double.parseDouble(l10);
l111 = 6 * O1000;
JOptionPane.showMessageDialog(null, “T\150e area \157f40t\150e40\143\165\142e: ” + l111, “r\145sult”, JOptionPane.INFORMATION_MESSAGE);
}
l1001 = JOptionPane.showInputDialog(“P\154ease40\143h\157s\145 \157ne of the options72″ + “12″ + “\141)\105\156\164e\162 61 \164o c\141\154culat\14540th\145 \141r\145a \157f40th\145 \103i\162cl\145″ + “12″ + “\14251\105\156\164e\162 62 to \143\141lculat\14540th\145 \141re\141 \157f40\164h\145 \124r\151an\147le” + “12″ + “c51\105\156ter 340t\157 \143alc\165\154ate th\14540ar\145a40of40t\150\145 \123q\165a\162e” + “12″ + “\144)Ente\16240440t\157 \143alc\165\154ate th\14540a\162\145\14140o\146 \164\150e40R\145c\164a\156g\154e” + “12″ + “\145)Ent\145\162 65 \164o40\143\141\154\143ula\164\145 \164\150\14540a\162ea40o\146 \164h\145 C\165b\145″ + “12″ + “\146)\105\156\164e\162 66 \164o \145\170it t\150e40\160r\157\147r\141m”);
l100 = Double.parseDouble(l1001);
}
System.out.println(“\120r\157\147\162a\155 \164e\162mi\156a\164ed12″);
System.exit(0);
}
}

Obfuscated Symbol Cross Reference

The obfuscator produces a cross reference mapping obfuscated symbols to the orginal symbols, so that obfuscated code in the field can still be decoded if necessary. In fact, by reversing this map, the obfuscator can unobfuscate the code (of course, it cannot restore the comments).

Double -> Double
INFORMATION_MESSAGE -> INFORMATION_MESSAGE
JOptionPane -> JOptionPane
Math -> Math
PI -> PI
Program1 -> Program1
String -> String
System -> System
area -> l111
args -> l1
choice -> l100
exit -> exit
first -> l10
javax -> javax
length -> O1000
out -> out
parseDouble -> parseDouble
println -> println
radius -> O101
second -> O11
showInputDialog -> showInputDialog
showMessageDialog -> showMessageDialog
swing -> swing
value -> l1001
width -> l110

Follow

Get every new post delivered to your Inbox.