Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Sun May 09, 2021 9:05 pm

I am trying to figure out how to add String data to a document (without loading a document from the laptop harddrive). I need to set the SUBJECT line, the DATE line, and the AUTH line after setting the heading. Quite frankly I can not understand the transition from the sample java docs to an actual formatted document as attached. This is my first attempt at using the Spire.Doc jar.


public void CreateWORDDocument() throws IOException{

Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat( "ddMMyyyy");
date = df.format(dt);

filename = "C:\\Users\\wmelendez\\Documents\\NetBeansProjects\\PlumbPRO\\NewDOC";
String Line4 = "SUBJ: Report of Projects & Costs";
String Line2 = "DATE: '"+ date + "' ";
String Line3 ="AUTH: Brian Williams, brian.williams@realpage.com";



//Create word document.
Document document =new Document();

//Add a new section.
Section section = document.addSection();
//Add a section

//Add a new paragraph.
Paragraph paragraph = section.addParagraph();

//Append Text.
paragraph.appendText(jtxtarea_SUMMARY.getText());

//Save to file.
document.saveToFile(filename + "2 -"+ date + ".docx", FileFormat.Docx);

txguy5199
 
Posts: 5
Joined: Sun May 09, 2021 7:27 pm

Mon May 10, 2021 6:32 am

Hello,

Thanks for your inquiry.
For the sample document provided in your attachment, please refer to the following code to achieve it.
If there are any issues, just feel free to contact us.
Code: Select all
    public static void CreateWORDDocument() throws IOException {

        Date dt = new Date();
        SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
        String date = df.format(dt);
        String date2 = new SimpleDateFormat("EEEE, MMM dd, yyyy").format(dt);

        String filename = "C:\\Users\\wmelendez\\Documents\\NetBeansProjects\\PlumbPRO\\newDoc";
        String Line4 = "SUBJ: Report of Projects & Costs";
        String Line2 = "DATE: '"+ date2 + "' ";
        String Line3 ="AUTH: Brian Williams, brian.williams@realpage.com";

        Document document = new Document();
        CharacterFormat format = new CharacterFormat(document);
        format.setFontName("calibri");
        format.setFontSize(10);
        Section section = document.addSection();
        section.addParagraph().appendText(Line4);
        section.addParagraph().appendText(Line2);
        section.addParagraph().appendText(Line3);
        section.addParagraph();
        section.addParagraph().appendText("Start Date:  _____________   End Date:_________________");
        section.addParagraph();
        section.addParagraph();
        section.addParagraph().appendText("Project Name:__________________________________________CRM Number:_____    Unit Count: _____");
        section.addParagraph().appendText("Project Address: ____________________________________________________");
        section.addParagraph().appendText("City: ______________________________________ State _____________________");
        section.addParagraph();
        Paragraph paragraph1 = section.addParagraph();
        CharacterFormat fformat = new CharacterFormat(document);
        fformat.setTextColor(Color.red);
        fformat.setFontName("calibri");
        fformat.setFontSize(10);
        paragraph1.appendText("Permit: ").applyCharacterFormat(format);

        TextRange textRange1 = paragraph1.appendText("NO");
        textRange1.applyCharacterFormat(fformat);
        paragraph1.appendText("\tLabor Costs: ").applyCharacterFormat(format);
        TextRange textRange2 = paragraph1.appendText("YES");
        textRange2.applyCharacterFormat(fformat);
        paragraph1.appendText("\tParts Required: ").applyCharacterFormat(format);
        TextRange textRange3 = paragraph1.appendText("NO");
        textRange3.applyCharacterFormat(fformat);

        Paragraph paragraph2 = section.addParagraph();
        paragraph2.appendText("Type Project: ").applyCharacterFormat(format);
        TextRange textRange4 = paragraph2.appendText("New Construction");
        textRange4.applyCharacterFormat(fformat);

        section.addParagraph();
        section.addParagraph().appendText("POC:\t\t\t\t\t\tPhone:\t\t\t");
        section.addParagraph().appendText("POC eMail: \t\t\t");
        section.addParagraph();
        section.addParagraph().appendText("POC eMail: \t\t\t");
        section.addParagraph();
        section.addParagraph().appendText("Action Summary:");
        section.addParagraph();
        section.addParagraph().appendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam hendrerit nisi sed sollicitudin pellentesque. Nunc posuere purus rhoncus pulvinar aliquam. Ut aliquet tristique nisl vitae volutpat. Nulla aliquet porttitor venenatis. Donec a dui et dui fringilla consectetur id nec massa. Aliquam erat volutpat. Sed ut dui ut lacus dictum fermentum vel tincidunt neque. Sed sed lacinia lectus. Duis sit amet sodales felis. Duis nunc eros, mattis at dui ac, convallis semper risus. In adipiscing ultrices tellus, in suscipit massa vehicula eu.");
        section.addParagraph();
        section.addParagraph();
        section.addParagraph().appendText("SubTotals: \t  Tax Percentage: \t   Margin/Markup:  \t    Total Costs: _______                  ");
        section.addParagraph();
        section.addParagraph().appendText("\t");
        Table table = section.addTable();
        table.setColumnWidth(new float[]{340,80,70});
        table.addRow(3);table.addRow(3);table.addRow(3);table.addRow(3);
        table.addRow(3);table.addRow(3);table.addRow(3);table.addRow(3);
        table.getRows().get(0).getCells().get(0).addParagraph().appendText("LINE ITEMS");
        table.getRows().get(0).getCells().get(1).addParagraph().appendText("AMOUNT");
        table.getRows().get(0).getCells().get(2).addParagraph().appendText("COSTS");

        for(int i=0; i< table.getRows().getCount();i++){
            for(int j=0; j< table.getRows().get(i).getCells().getCount();j++){
                table.getRows().get(i).getCells().get(j).getCellFormat().getBorders().setLineWidth(1);
                for(int k=0 ;k<table.getRows().get(i).getCells().get(j).getParagraphs().getCount();k++){
                    Paragraph paragraph = table.getRows().get(i).getCells().get(j).getParagraphs().get(k);
                    for (int x=0;x<paragraph.getChildObjects().getCount();x++){
                        if(paragraph.getChildObjects().get(x).getDocumentObjectType() == DocumentObjectType.Text_Range){
                            TextRange textRange = (TextRange) paragraph.getChildObjects().get(x);
                            textRange.applyCharacterFormat(format);
                        }
                    }
                }
            }
        }
        section.addParagraph();
        section.addParagraph();

        for(int i=0 ;i<section.getParagraphs().getCount();i++){
            Paragraph paragraph = section.getParagraphs().get(i);
            if(paragraph != paragraph1 && paragraph != paragraph2){
                for (int j=0;j<paragraph.getChildObjects().getCount();j++){
                    if(paragraph.getChildObjects().get(j).getDocumentObjectType() == DocumentObjectType.Text_Range){
                        TextRange textRange = (TextRange) paragraph.getChildObjects().get(j);
                        textRange.applyCharacterFormat(format);
                    }
                }
            }
        }

        document.saveToFile(filename + "2 -" + date + ".docx", FileFormat.Docx);
    }


Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Tue May 11, 2021 3:45 pm

What are the Spire.Doc "imports" for the method solution, please? My program seems stuck -not recognizing the Spire.Doc classes.

txguy5199
 
Posts: 5
Joined: Sun May 09, 2021 7:27 pm

Tue May 11, 2021 11:30 pm

Never mind. I figured out the imports by reading the API sheet. I do have another question though. This is in reference to using CharacterFormat format vs TextRange. Thye each use a different format for handling fonts. Is there a way to look up the CharacterFormat format and see what different options are available?

txguy5199
 
Posts: 5
Joined: Sun May 09, 2021 7:27 pm

Wed May 12, 2021 8:37 am

Hello,

Thanks for your response.
Please note that “CharacterFormat” is used to set the format of “TextRange”, including the font format, color , border, etc. You can create a new CharacterFormat style and then apply it to the “TextRange”, or get the existing CharacterFormat property and modify the style, like the following code.

Code: Select all
//...
textRange.getCharacterFormat().setFontName("Arial");
textRange.getCharacterFormat().setTextColor(Color.red);
//...


Besides, about the "look up the CharacterFormat" you said, do you want to know the usage of “CharacterFormat”? If so, you can visit the following link.
https://www.e-iceblue.com/api_documents ... ormat.html
Or if I misunderstood, please describe your needs in detail.

Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Wed May 12, 2021 8:19 pm

Thanks. Yes that was what I was looking for. Thank you for your explanation of how the CharacterFormat and TextRange work together. I noticed that in the previous response, the way that fonts were defined was as follow:
CharacterFormat format = new CharacterFormat(document);
format.setFontName("calibri");
format.setFontSize(10);
Hence my question as to the differences. Its my understanding that Format.setFontName and Format.setFontSize within CharacterFormat is java poi derived? Am I confusing the issue?

By the way I did modify the sample you guys did for me. Really appreciate you doing this and directing me as to how to implement the MS WORD portion of Spire.Doc with JAVA. The data comes from a JAVA entry form (NetBeans 8.2) or the SQL database and the Spire.Doc jar files places it into the MS Word document for reporting. However, I still have to complete the line Item nomenclature, amount, and pricing.

Again THANKS!! Great Learning Experience for me. When I complete the Report, I'll post the JAVA Method and the sample document for others who may still need to see how it was done.

txguy5199
 
Posts: 5
Joined: Sun May 09, 2021 7:27 pm

Thu May 13, 2021 3:27 am

Hello,

Thanks for your response and glad to hear that my answer is helpful to you.

Besides, our Spire.Doc is based on Microsoft Word, it follows the Standard of Microsoft Word. For these properties (font name, font size, color, etc.), our product gets them by parsing the internal data of the Word file, not derived from java poi.

If you have any other questions while using our products, just feel free to contact us.

Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Sun May 16, 2021 4:52 pm

Support:

You guys really do know how to be supportive. Thank you.

I do have one thing that, somehow I can't figure out, doesn't seem to work in the software method I wrote. I placed a red rectangle around the section that will is the only portion that accepts the calibri 10 pt font style. The rest of the document defaults to New Times Roman font . I've attached the final MS Word document created and also a copy of the code in an MS Word format.

(1) What I am needing is to have all the fonts the same.
(2) Also, if you would, can you show me how to center the variables in the rows.
(3) is there a reference URL for "color" selection?

Code: Select all

public static void CreateWORDDocument() throws IOException {
       
     if(jrbtn_PERMIT.isSelected()){newPERMIT="YES";}else {newPERMIT="NO";}
     if(jrbtn_LABORCOSTS.isSelected()){newLABOR="YES";}else {newLABOR="NO";}
     if(jrbtn_PARTSCOSTS.isSelected()){newPARTS="YES";}else {newPARTS="NO";}

        Date dt = new Date();
        SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
        String date = df.format(dt);
        String date2 = new SimpleDateFormat("EEEE, MMM dd, yyyy").format(dt);
       //newfile = "C:\\Users\\wmelendez\\Documents\\NetBeansProjects\\PlumbPRO\\Plumb123.docx";
        newfile = filename;
        String Line1 = "SUBJ: Report of Projects & Costs";
        String Line2 = "DATE: '"+ date2 + "' ";
        String Line3 ="AUTH: Brian Williams, brian.williams@realpage.com";

        Document document = new Document();
        CharacterFormat format = new CharacterFormat(document);
        format.setFontName("calibri");
        format.setFontSize(10);
       //START SECTION
        Section section = document.addSection();
        section.addParagraph().appendText(Line1);
        section.addParagraph().appendText(Line2);
        section.addParagraph().appendText(Line3);
        section.getPageSetup().setPageSize(PageSize.A4);
        section.getPageSetup().getMargins().setTop(72f);
        section.getPageSetup().getMargins().setBottom(72f);
        section.getPageSetup().getMargins().setLeft(89.85f);
        section.getPageSetup().getMargins().setRight(89.85f);
        section.addParagraph();
        section.addParagraph().appendText("Start Date:"+  jtxtfld_STARTDATE.getText() +  "     End Date:"    +jtxtfld_ENDDATE.getText()+"" );
        section.addParagraph();
        section.addParagraph().appendText("Project Name:  "+ jtxtfld_PROJECTNAME.getText() + "  CRM Number: "+jtxtfld_CRM.getText()+"  Unit Count:"+jtxtfld_UNITCOUNT.getText()+"");
        section.addParagraph().appendText("City: "+jtxtfld_CITY.getText()+"             State: "+jcbo_STATE.getSelectedItem()+"");
        section.addParagraph();
        section.addParagraph().appendText("POC:  "+jtxtfld_CONTACT.getText()+"");
        section.addParagraph().appendText("POC eMail:  "+jtxtfld_EMAILPHONE.getText()+" ");
        section.addParagraph();
        Paragraph paragraph1 = section.addParagraph();
        CharacterFormat fformat = new CharacterFormat(document);
        fformat.setTextColor(Color.black);
        fformat.setFontName("calibri");
        fformat.setFontSize(10);
          TextRange textRange1 = paragraph1.appendText(" ");
       
        //paragraph1.appendText("Permit: ").applyCharacterFormat(fformat);
        textRange1 = paragraph1.appendText("Permit:  "+ newPERMIT +"");
        textRange1.applyCharacterFormat(fformat);
        textRange1 = paragraph1.appendText("\t\t Labor Costs:  "+newLABOR+"");
        textRange1.applyCharacterFormat(fformat);
        paragraph1.appendText("\t\t Parts Required:  "+newPARTS+" ").applyCharacterFormat(fformat);
        paragraph1.appendText("Type Project:   "+jcbo_TYPE.getSelectedItem()+" ").applyCharacterFormat(fformat);
        section.addParagraph();
        section.addParagraph().appendText("\t");
         
        section.addParagraph().appendText("Action Summary:  ");
        section.addParagraph();
        section.addParagraph().appendText(""+jtxtarea_SUMMARY.getText()+"");
        section.addParagraph();
             
        section.addParagraph().appendText("SubTotals: "+PRO1+" ");
        section.addParagraph().appendText("Tax Percentage: "+ PRO2 +"   ");
        section.addParagraph().appendText("Margin/Markup: "+ PRO3 +"  ");
        section.addParagraph().appendText("Total Costs:  "+ PRO4 +"  ");
        section.addParagraph();
        section.addParagraph().appendText("\t");
       
        //*******START TABLE SECTION******
        //Set the table headers
       
        Table table = section.addTable();
        table.setColumnWidth(new float[]{200,10,30});
        table.setDefaultRowHeight(10);
        table.applyStyle(DefaultTableStyle.Colorful_List);
       
        //set top border of table
   table.getTableFormat().getBorders().getTop().setBorderType(BorderStyle.Hairline);
   table.getTableFormat().getBorders().getTop().setLineWidth(1.0F);
   table.getTableFormat().getBorders().getTop().setColor(Color.BLACK);
   

        //set right border of table
   table.getTableFormat().getBorders().getRight().setBorderType(BorderStyle.Hairline);
   table.getTableFormat().getBorders().getRight().setLineWidth(1.0F);
   table.getTableFormat().getBorders().getRight().setColor(Color.BLACK);
       
        //set left border of table

        table.getTableFormat().getBorders().getLeft().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getLeft().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getLeft().setColor(Color.BLACK);

   //set bottom border of table
   table.getTableFormat().getBorders().getBottom().setBorderType(BorderStyle.Hairline);

        //set vertical and horizontal border
   table.getTableFormat().getBorders().getVertical().setBorderType(BorderStyle.Hairline);
   table.getTableFormat().getBorders().getHorizontal().setBorderType(BorderStyle.Hairline);
   table.getTableFormat().getBorders().getVertical().setColor(Color.BLACK);


       
               
        table.addRow(3);table.addRow(3);table.addRow(3);table.addRow(3);
        table.addRow(3);table.addRow(3);table.addRow(3);table.addRow(3);
        table.getRows().get(0).getCells().get(0).addParagraph().appendText("LINE ITEMS");
       table.getRows().get(0).getCells().get(1).addParagraph().appendText("AMOUNT");
       table.getRows().get(0).getCells().get(2).addParagraph().appendText("COSTS");
        String[] header = {"LINE ITEM", "AMOUNT","COST"};
        String[][] data =
                {
                        new String[]{PRO5,  PRO6,  PRO7},
                        new String[]{PRO8,  PRO9,  PRO10},
                        new String[]{PRO11, PRO12, PRO13},
                        new String[]{PRO14, PRO15, PRO16},
                        new String[]{PRO17, PRO18, PRO19},
                        new String[]{PRO20, PRO21, PRO22},
                        new String[]{PRO23, PRO24, PRO25},
                        new String[]{PRO26, PRO27, PRO28},
                        new String[]{PRO29, PRO30, PRO31},
                        new String[]{PRO32, PRO33, PRO34},
                        new String[]{PRO35, PRO36, PRO37},
                        new String[]{PRO38, PRO39, PRO40},
                };
         //Add a table
       

        //set the rows and columns for the table
        table.resetCells(14,3);

        //Auto fit column widths to window
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Set the first row as table header and add data
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(15);
        row.setHeightType(TableRowHeightType.Exactly);
        row.getRowFormat().setBackColor(new Color(173, 216, 230));
      //row.getRowFormat().setBackColor(Color.white);
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange range1 = p.appendText(header[i]);
            range1.getCharacterFormat().setFontName("calibri");
            range1.getCharacterFormat().setFontSize(11f);
            range1.getCharacterFormat().setBold(true);
        }//END OF HEADER ROW SETUP

        //add data to the rest of rows
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            // dataRow.getRowFormat().setBackColor(Color.light gray);
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
                range2.getCharacterFormat().setFontName("Calibri");
                range2.getCharacterFormat().setFontSize(10f);
            }
        }

        //Set background color for cells
       
     
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 0; f < row2.getCells().getCount(); f++) {
                     row2.getCells().get(f).getCellFormat().setBackColor(Color.white);
                   
                    //row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
                   
                }
            }
        }
        //Save the document
         document.saveToFile(newfile + "-" + date + ".docx", FileFormat.Docx);
    }









txguy5199
 
Posts: 5
Joined: Sun May 09, 2021 7:27 pm

Mon May 17, 2021 3:34 am

Hello,

Thanks for your response.
Regarding your issues, please find the answers below.

(1) To keep all the text the same font, please add this code before saving the file.
Code: Select all
for(int i=0 ;i<section.getParagraphs().getCount();i++){
    Paragraph paragraph = section.getParagraphs().get(i);
    for (int j=0;j<paragraph.getChildObjects().getCount();j++){
        if(paragraph.getChildObjects().get(j).getDocumentObjectType() == DocumentObjectType.Text_Range){
            TextRange textRange = (TextRange) paragraph.getChildObjects().get(j);
            textRange.getCharacterFormat().setFontName("Calibri ");
        }
    }
}

(2) Please refer to the following code snippet to set the Horizontal Alignment of the paragraph in rows to center.
Code: Select all
//add data to the rest of rows
for (int r = 0; r < data.length; r++) {
    TableRow dataRow = table.getRows().get(r + 1);
    dataRow.setHeight(25);
    dataRow.setHeightType(TableRowHeightType.Exactly);
    // dataRow.getRowFormat().setBackColor(Color.light gray);
    for (int c = 0; c < data[r].length; c++) {
        dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
        Paragraph paragraph = dataRow.getCells().get(c).addParagraph();
        paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        TextRange range2 = paragraph.appendText(data[r][c]);
        range2.getCharacterFormat().setFontName("Calibri");
        range2.getCharacterFormat().setFontSize(10f);
    }
}

(3) Regarding the "color", you can visit the following link.
https://docs.oracle.com/javase/8/docs/a ... Color.html

Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Fri May 21, 2021 7:38 am

Hello,

Greeting from E-iceblue!
Did the code we provided work for you? Any feedback will be greatly appreciated.

Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Return to Spire.Doc