MailMerge Example using PHP code

Hi, Sunill,

Aspose.Words itself doesn’t communicate directly with MS Access, MySQL, MS Excel, etc. It uses java.sql.Result to isolate data from data-provider application (as many other multi-tier applications do).

MS Access used in Aspose.Words for Java demos while this is conventional configuration for testing. Really you can use any data source of your choice. But previously you have to get valid java.sql.ResultSet from your concrete data file.

You can check MySql documentation how to get java.sql.ResultSet from MySql data files. I believe this is standard operation for MySql.

And you can check your ResultSets before start using them in MailMerge. Firstly, the ResultSet doesn’t be nullJ Second, you can play a little with your ResultSet to be sure it alive:

String tableName = resultSet.getMetaData().getTableName(1);

//iterate resultset

while (resultSet.next())

{

int curRow = resultSet.getRow();

Object obj = resultSet.getObject(1);

}

Best Regards,

Hi

You can use the following connection string to connect to XLS.

//Load a DB driver that is used by the demos

Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver”);

//Compose connection string.

String connectionString = “jdbc:odbc:DRIVER={Microsoft Excel Driver (*.xls)};DBQ=C:\Temp\test.xls;UID=Admin”;

Also see the following link.

http://xytang.blogspot.com/2008/02/how-to-connect-to-excel-spreadsheet.html

Best regards.

hi

thank you for your support , but could you able to give me an example on how to write data in .xls file using the PHP and how do the Aspose.words document is generated using this .xls file

with regards

sunil satushe

Hi

The technique of generating documents using XLS files as datasource is the same as if you use any other datasource (mySql, MS Access, MSSQL etc).

Please see the following link to learn how to read/write excel spreadsheets using PHP.

http://www.issociate.de/board/post/217694/Read/write_Excel_spreadsheet_libraries.html

Best regards.

hi

i am posting my code for review plz review it and plz send me the changes if neccesary

/***************RelationSet.java**************/

import java.sql.\*;
public class RelationSet {

public static ResultSet execQuery() {
try {
//"Create database query
String sqlString = "select \* from Users";
//Create statement
Statement stmt = createStatement();
//Return ResultSet object
return stmt.executeQuery(sqlString);
} catch(SQLException e) {
System.out.println(e);
} catch(Exception e1) {
System.out.println(e1);
}
return null;

}
private static Statement createStatement() throws Exception {
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/card";
//Load a DB driver that is used by the demos
Class.forName("com.mysql.jdbc.Driver").newInstance ();
//Compose connection string.
Connection connection = DriverManager.getConnection(url, userName, password);
//Return Statement
return connection.createStatement();
}
}

/***********Temp.php*********/

<?php 
require\_once("java/Java.inc"); 
echo"Load libraries";
java\_require("C:\\Program Files\\xampp\\htdocs\\JavaBridge\\WEB-INF\\lib\\Aspose.Words.jdk15.jar;C:\\Program Files\\xampp\\htdocs\\JavaBridge\\WEB-INF\\lib\\jaxen-1.1.jar;C:\\Program Files\\xampp\\htdocs\\JavaBridge\\WEB-INF\\lib\\RelationSet.jar");
$doc = new Java("com.aspose.words.Document", "C:\\Temp\\in.doc");

//Create ResultSet
$myResultSet = new Java("java.sql.ResultSet");
//creates an instance of my own class and executes a method of it: the database query
$myQueryResult = new Java("RelationSet"); 
$myResultSet = $myQueryResult->execQuery();
//Execute mailMerge
$doc->getMailMerge()->executeWithRegions("Users", $myResultSet);
//Save document
$doc->save("C:\\Temp\\out.doc");
?>

Hi

Thanks for your request. It seems that your code should work fine.

Best regards.

hi

thak you for revewing my code , but on my localhost i do getting some problem over the $doc->getMailMerge()->executeWithRegions(“users”,$myResultSet); as NullpointerException as resultset to null,could i know which version of mysql as well as the mysql-connector-java-.jar you have used for reviewing for my code as well as the web-server

with regards

sunil satushe

Hi

Sorry. I missed to tell you that you should also use “mysql-connector-java”. You can download it from here.

http://dev.mysql.com/downloads/connector/j/5.1.html

and use the following PHP code.

<?php

require\_once("http://localhost:8080/JavaBridge/java/Java.inc");

//Load libraries

java\_require("packages\Aspose.Words.jdk15.jar;packages\jaxen-1.1.jar;packages\RelationSet.jar;packages\mysql-connector-java-5.1.6-bin.jar");

//Open document

$doc = new Java("com.aspose.words.Document", "C:\\Temp\\in.doc");

//Create ResultSet

$myResultSet = new Java("java.sql.ResultSet");

//creates an instance of my own class and executes a method of it: the database query

$myQueryResult = new Java("RelationSet"); 

$myResultSet = $myQueryResult->execQuery();

//Execute mailMerge

$doc->getMailMerge()->executeWithRegions("Users", $myResultSet);

//Save document

$doc->save("C:\\Temp\\out.doc");

?>

I hope this could help you.

Best regards.

hello sir ,

will you able to tell me what step should i follow to install a php-java-bridge on Linux server, any document or guideline to carry out the step

with regards

sunil satushe

Hi

Thanks for your inquiry. You can find step-by-step manual here.

http://php-java-bridge.sourceforge.net/pjb/installation.php

Hope this helps.

Best regards.

hello sir

i am siple creating a .doc file on Linux O.S. by using the aspose.words library.but i am facing the fatal error problem stating that FileNotFoundException. iam postin you the Test1.php code as well as the error stated page for your reference. i have created the Document Folder under the javabridge folder. the whole idea will be getting you through the Code snippets

******************Test1.php***********

<?php require\_once("java/Java.inc");
java\_autoload();
?>
<?php header("Content-type: text/html; charset=UTF-8"); 
java\_require("<http://webapplication1/javabridge/WEB-INF/lib/Aspose.Words.jdk15.jar;http://webapplication1/javabridge/WEB-INF/lib/jaxen-1.1.jar>"); 

//Object Instations 
$doc = new Java("com.aspose.words.Document");
$builder = new Java("com.aspose.words.DocumentBuilder");
$color = new Java("java.awt.Color");
$underline = new Java("com.aspose.words.Underline"); 
$textureindex= new Java("com.aspose.words.TextureIndex");
$lineStyle = new Java("com.aspose.words.LineStyle");
$bordertype = new Java("com.aspose.words.BorderType");
$paragraphAlignment = new Java("com.aspose.words.ParagraphAlignment");
$heightRule = new Java("com.aspose.words.HeightRule");
$cellAlignment = new Java("com.aspose.words.CellVerticalAlignment");
$breakType = new Java("com.aspose.words.BreakType"); 
$paperSize = new Java("com.aspose.words.PaperSize");
$Orientation = new Java("com.aspose.words.Orientation"); 

echo"You are now now at the Beginging of Creating the Aspose words using Java 
";
$builder->setDocument($doc);
$builder->setBold(true);
$builder->write("Hello world!");
$builder->write("The Php-Java Bridge Has Completed We have done this !!!!");

echo"Specify font formatting before adding text.
";
$builder->getFont()->setSize(16.0);
$builder->getFont()->setBold(true);
$builder->getFont()->setColor($color->BLUE);
$builder->getFont()->setName("Arial");
$builder->setUnderline($underline->DASH);
$builder->write("This text");
$builder->setUnderline($underline->NONE);
$builder->write(" is inserted at the beginning of the document and demonstrates ");

echo"Set shading and border around a run of text, then clear the border.
";
$builder->getFont()->getShading()->setForegroundPatternColor($color->CYAN);
$builder->getFont()->getShading()->setTexture($textureindex->TEXTURE\_SOLID);
$builder->write("various font");
$builder->getFont()->getShading()->clearFormatting();
$builder->getFont()->getBorder()->setLineStyle($lineStyle->SINGLE);
$builder->write(" formatting ");
$builder->getFont()->getBorder()->clearFormatting();
$builder->writeln("options.");
$builder->insertParagraph();

echo"Specify paragraph formatting before calling InsertParagraph or Writeln.
";
$builder->getParagraphFormat()->getBorders()->get($bordertype->TOP)->setLineStyle($lineStyle->DOUBLE);
$builder->getParagraphFormat()->getBorders()->get($bordertype->TOP)->setLineWidth(2.0);
$builder->getParagraphFormat()->setAlignment($paragraphAlignment->CENTER);
$builder->getParagraphFormat()->getShading()->setForegroundPatternColor($color->CYAN);
$builder->getParagraphFormat()->getShading()->setTexture($textureindex->TEXTURE\_SOLID);
$builder->getParagraphFormat()->setLeftIndent(2.0 \* 72.0); //2 inchdes by 72 points.
$builder->getParagraphFormat()->setSpaceBefore(12.0);
$builder->getParagraphFormat()->setSpaceAfter(12.0);
$builder->getFont()->setName("Arial");
$builder->getFont()->setSize(12.0);
$builder->write("This fragment demonstrates use of paragraph formatting to specify ");
$builder->writeln("alignment, spacing, borders and shading.");
$builder->getParagraphFormat()->clearFormatting();

echo"Create a fancy looking table inside the document.
";
// buildChessBoard(builder);
$builder->getFont()->clearFormatting();
$builder->getParagraphFormat()->clearFormatting();

$builder->insertParagraph();
$builder->writeln("This shows how to build a table in a document.");

$builder->getFont()->setSize(6.0);
$builder->getFont()->setName("Tahoma");
$builder->getParagraphFormat()->setAlignment($paragraphAlignment->CENTER);

echo"It is possible to change row format before (like here) and also during creation of the row.
";
$builder->getRowFormat()->setHeight(0.4 \* 72); //0.4"
$builder->getRowFormat()->setHeightRule($heightRule->EXACTLY);

echo"It is possible to change cell format before (like here) and also during creation of the cell.
";
$builder->getCellFormat()->setWidth(0.4 \* 72); //0.4"
$builder->getCellFormat()->setVerticalAlignment($cellAlignment->CENTER);

$borders = $builder->getCellFormat()->getBorders();
$borders->setLineStyle($lineStyle->SINGLE);
$borders->setLineWidth(2.0);
$borders->setColor($color->BLUE);

for ($y = 0; $y < 8; $y++)
{
for ($x = 0; $x < 8; $x++)
{
$builder->insertCell();
$builder->write("X" + $x + ", Y" + $y);

//This alternatives cell backgrounds.
$isBlack = ((($x + $y) & 0x01) != 0);
$builder->getCellFormat()->getShading()->setBackgroundPatternColor(
(isBlack) ? $color->BLACK : $color->WHITE);
}
$builder->endRow();
}
$builder->endTable();

echo"Insert another section and demonstrate page setup properties.
";
$builder->getFont()->setSize(12.0);
$builder->insertBreak($breakType->SECTION\_BREAK\_NEW\_PAGE);
$builder->getPageSetup()->setPaperSize($paperSize->A5);
$builder->getPageSetup()->setOrientation($Orientation->LANDSCAPE);
$builder->writeln("This text is in a section with different page size and orientation.");

$builder->getFont()->clearFormatting();
$builder->getFont()->setItalic(true);
$builder->write("This text is inserted into the header.");

$doc->save("http:///webapplication1//out.doc");

?>

***********end of Test1.php******************

error page for the Test1.php

You are now now at the Beginging of Creating the Aspose words using Java
Specify font formatting before adding text.
Set shading and border around a run of text, then clear the border.
Specify paragraph formatting before calling InsertParagraph or Writeln.
Create a fancy looking table inside the document.
It is possible to change row format before (like here) and also during creation of the row.
It is possible to change cell format before (like here) and also during creation of the cell.
Insert another section and demonstrate page setup properties.

**Fatal error**: Uncaught [[o:Exception]:"java.lang.Exception: Invoke failed: [[o:Document]]->save((o:String)[o:String]). Cause: java.io.FileNotFoundException: Document/out.doc (No such file or directory) VM: 1.6.0\_05@http://java.sun.com/" at: #-14 java.io.RandomAccessFile.open(Native Method) #-13 java.io.RandomAccessFile.(Unknown Source) #-12 java.io.RandomAccessFile.(Unknown Source) #0 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(265): java\_ThrowExceptionProxyFactory->getProxy(348, '@V', true) #1 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(417): java\_Arg->getResult(true) #2 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(423): java\_Client->getWrappedResult(true) #3 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(627): java\_Client->getResult() #4 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(1753): java\_Client->invokeMethod(1, 'save', Array) #5 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(1866): java\_JavaProxy->\_\_call('save', Array) #6 /home/thinkbiz/public\_ht in **/home/thinkbiz/public\_html/my/javabridge/java/Java.inc** on line **228**

Hi

Thanks for your request. You can’t save a document to http location. I think that you can try using the following code.

$doc->save("out.doc");

I hope this could help you.

Best regards.

hello sir ,

could you able to tell us how this MailMerge functionality is carried out with the Aspose.words, i have done it on the Windows now i am trying out for the Linux . i mean to say wheather we need the in.doc file where we specifice the MailMerge Functionality and after processing this in.doc file with the database it will create the out.doc file so to carry out the mailmerge fucntionality, is it necessary to have this in.doc file if there is other way to carry out the please update me

thank you

sunil satushe

Hi

There are no differences between implementing mail merge functionality on Windows and on Linux platform. So you should have template document (in.doc).

Best regards.

**Fatal error**: Uncaught [[o:Exception]:"java.lang.Exception: CreateInstance failed: new com.aspose.words.Document. Cause: java.lang.ClassNotFoundException: Unresolved external reference: java.lang.NoClassDefFoundError: sun.nio.cs.ThreadLocalCoders. -- Unable to call constructor, see the README section "Java platform issues" for details. VM: 1.4.2@http://gcc.gnu.org/java/" at: #-6 php.java.bridge.JavaBridge.getUnresolvedExternalReferenceException(JavaBridge.java:427) #-5 php.java.bridge.JavaBridge.CreateObject(JavaBridge.java:498) #-4 php.java.bridge.Request.handleRequest(Request.java:447) #0 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(265): java\_ThrowExceptionProxyFactory->getProxy(1, NULL, false) #1 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(417): java\_Arg->getResult(false) #2 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(420): java\_Client->getWrappedResult(false) #3 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(602): java\_Client->getInternalResult() #4 /home/thinkbiz/public\_html/my in **/home/thinkbiz/public\_html/my/javabridge/java/Java.inc** on line **228**

Hi

Thanks for your request. Could you please provide me code that will allow me to reproduce this issue and attach your document if it is needed? I will try to reproduce this issue on my side and help you.

Best regards.

<?php require\_once("java/Java.inc");
java\_autoload();
?>
<?php header("Content-type: text/html; charset=UTF-8"); 
java\_require("<http://webapplication1/javabridge/WEB-INF/lib/Aspose.Words.jdk15.jar;http://webapplication1/javabridge/WEB-INF/lib/jaxen-1.1.jar>"); 

//Object Instations 
$doc = new Java("com.aspose.words.Document");
$builder = new Java("com.aspose.words.DocumentBuilder");
$color = new Java("java.awt.Color");
$underline = new Java("com.aspose.words.Underline"); 
$textureindex= new Java("com.aspose.words.TextureIndex");
$lineStyle = new Java("com.aspose.words.LineStyle");
$bordertype = new Java("com.aspose.words.BorderType");
$paragraphAlignment = new Java("com.aspose.words.ParagraphAlignment");
$heightRule = new Java("com.aspose.words.HeightRule");
$cellAlignment = new Java("com.aspose.words.CellVerticalAlignment");
$breakType = new Java("com.aspose.words.BreakType"); 
$paperSize = new Java("com.aspose.words.PaperSize");
$Orientation = new Java("com.aspose.words.Orientation"); 

echo"You are now now at the Beginging of Creating the Aspose words using Java 
";
$builder->setDocument($doc);
$builder->setBold(true);
$builder->write("Hello world!");
$builder->write("The Php-Java Bridge Has Completed We have done this !!!!");

echo"Specify font formatting before adding text.
";
$builder->getFont()->setSize(16.0);
$builder->getFont()->setBold(true);
$builder->getFont()->setColor($color->BLUE);
$builder->getFont()->setName("Arial");
$builder->setUnderline($underline->DASH);
$builder->write("This text");
$builder->setUnderline($underline->NONE);
$builder->write(" is inserted at the beginning of the document and demonstrates ");

echo"Set shading and border around a run of text, then clear the border.
";
$builder->getFont()->getShading()->setForegroundPatternColor($color->CYAN);
$builder->getFont()->getShading()->setTexture($textureindex->TEXTURE\_SOLID);
$builder->write("various font");
$builder->getFont()->getShading()->clearFormatting();
$builder->getFont()->getBorder()->setLineStyle($lineStyle->SINGLE);
$builder->write(" formatting ");
$builder->getFont()->getBorder()->clearFormatting();
$builder->writeln("options.");
$builder->insertParagraph();

echo"Specify paragraph formatting before calling InsertParagraph or Writeln.
";
$builder->getParagraphFormat()->getBorders()->get($bordertype->TOP)->setLineStyle($lineStyle->DOUBLE);
$builder->getParagraphFormat()->getBorders()->get($bordertype->TOP)->setLineWidth(2.0);
$builder->getParagraphFormat()->setAlignment($paragraphAlignment->CENTER);
$builder->getParagraphFormat()->getShading()->setForegroundPatternColor($color->CYAN);
$builder->getParagraphFormat()->getShading()->setTexture($textureindex->TEXTURE\_SOLID);
$builder->getParagraphFormat()->setLeftIndent(2.0 \* 72.0); //2 inchdes by 72 points.
$builder->getParagraphFormat()->setSpaceBefore(12.0);
$builder->getParagraphFormat()->setSpaceAfter(12.0);
$builder->getFont()->setName("Arial");
$builder->getFont()->setSize(12.0);
$builder->write("This fragment demonstrates use of paragraph formatting to specify ");
$builder->writeln("alignment, spacing, borders and shading.");
$builder->getParagraphFormat()->clearFormatting();

echo"Create a fancy looking table inside the document.
";
// buildChessBoard(builder);
$builder->getFont()->clearFormatting();
$builder->getParagraphFormat()->clearFormatting();

$builder->insertParagraph();
$builder->writeln("This shows how to build a table in a document.");

$builder->getFont()->setSize(6.0);
$builder->getFont()->setName("Tahoma");
$builder->getParagraphFormat()->setAlignment($paragraphAlignment->CENTER);

echo"It is possible to change row format before (like here) and also during creation of the row.
";
$builder->getRowFormat()->setHeight(0.4 \* 72); //0.4"
$builder->getRowFormat()->setHeightRule($heightRule->EXACTLY);

echo"It is possible to change cell format before (like here) and also during creation of the cell.
";
$builder->getCellFormat()->setWidth(0.4 \* 72); //0.4"
$builder->getCellFormat()->setVerticalAlignment($cellAlignment->CENTER);

$borders = $builder->getCellFormat()->getBorders();
$borders->setLineStyle($lineStyle->SINGLE);
$borders->setLineWidth(2.0);
$borders->setColor($color->BLUE);

for ($y = 0; $y < 8; $y++)
{
for ($x = 0; $x < 8; $x++)
{
$builder->insertCell();
$builder->write("X" + $x + ", Y" + $y);

//This alternatives cell backgrounds.
$isBlack = ((($x + $y) & 0x01) != 0);
$builder->getCellFormat()->getShading()->setBackgroundPatternColor(
(isBlack) ? $color->BLACK : $color->WHITE);
}
$builder->endRow();
}
$builder->endTable();

echo"Insert another section and demonstrate page setup properties.
";
$builder->getFont()->setSize(12.0);
$builder->insertBreak($breakType->SECTION\_BREAK\_NEW\_PAGE);
$builder->getPageSetup()->setPaperSize($paperSize->A5);
$builder->getPageSetup()->setOrientation($Orientation->LANDSCAPE);
$builder->writeln("This text is in a section with different page size and orientation.");

$builder->getFont()->clearFormatting();
$builder->getFont()->setItalic(true);
$builder->write("This text is inserted into the header.");

$doc->save("http:///webapplication1//out.doc");

?>

***********end of Test1.php******************

error page for the Test1.php

**Fatal error**: Uncaught [[o:Exception]:"java.lang.Exception: CreateInstance failed: new com.aspose.words.DocumentBuilder. Cause: java.lang.ClassNotFoundException: Unresolved external reference: java.lang.NoClassDefFoundError: sun.nio.cs.ThreadLocalCoders. -- Unable to call constructor, see the README section "Java platform issues" for details. VM: 1.4.2@http://gcc.gnu.org/java/" at: #-6 php.java.bridge.JavaBridge.getUnresolvedExternalReferenceException(JavaBridge.java:427) #-5 php.java.bridge.JavaBridge.CreateObject(JavaBridge.java:498) #-4 php.java.bridge.Request.handleRequest(Request.java:447) #0 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(265): java\_ThrowExceptionProxyFactory->getProxy(1, NULL, false) #1 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(417): java\_Arg->getResult(false) #2 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(420): java\_Client->getWrappedResult(false) #3 /home/thinkbiz/public\_html/my/javabridge/java/Java.inc(602): java\_Client->getInternalResult() #4 /home/thinkbiz/public\_ in **/home/thinkbiz/public\_html/my/javabridge/java/Java.inc** on line **228**

Hi

Thanks for additional information. I can’t reproduce this issue on my side. Your code works fine on my side (I attached output document). I used the latest version of Aspose.Words for testing. You can get it here:

The following two lines I inserted at the beginning of code:

require\_once("http://localhost:8080/JavaBridge/java/Java.inc"); 

java\_require("lib\Aspose.Words.jdk16.jar");

And used the following line to save document:

$doc->save("c:\\Temp\\out.doc");

Best regards.

hello sir

thank you for your assistance. but the code i am doing for the Linux O.s not for the Window’s. one thing i want to share with you that the code i have done was working fine in the pervious week , when the same code i review for this time it got stuck into this problem that it throws a ClassNotFoundException as com.aspose.words.Document not able to create an instance of this class but when i uncomment this one, the code work’s fine i.e it can get the other classes references smoothly i mean to say the classes com.aspose.words.LineStyle works fine so what is the exact problem

with regards

sunil satushe

Hi

I don’t think that there can be some difference between codes on Windows and on Linux platform. As an option try updating to the latest version of Aspose.Words for java. The latest version doesn’t require other jars, so you can use:

java\_require("lib\Aspose.Words.jdk15.jar");

Instead

java\_require("lib\Aspose.Words.jdk15.jar;lib\jaxen-1.1.jar");

Best regards.