the Internet Windows Android

1C ActiveX for Word Normal application. Creating an external printed form "Treaty"

Good day!

For most organizations, the standard print form of any treaty in 1C programs is not suitable. Therefore, the company 1C provided the ability to add additional printed forms for documents and other objects. In this article, I want to tell how to create and connect the external print form of the contract to be opened in Microsoft Word..

Connecting additional external printed forms

Start 1C: Enterprise. Open the "Additional External Printing Forms" directory through the "Service" menu - " Additional reports and processing. "

Click the "Add" button, then register a new printed form by clicking "Replacing External Processing File". Automatically fill the facilities printed form Document "Implementation of goods and services". Select "Treaty" in the "Printed Printing" column so that the standard printed form is no longer used.

We run 1C: Enterprise, open the "Counterparties" handbook, choose the counterparty for which our contract will be printed and the "Files" button will go to the "Storage" for more information", We load a template for a contract to it and, necessarily, call it a" contract ", as shown in the figure below, otherwise the program will not be able to find a layout for printed form.

Now open any document "Implementation of goods and services" and click the "Print" button - "Treaty". Microsoft Word document opens.

The external printed form "Treaty" and layout to it can be downloaded on the links below.

Layout of the employment contract in Microsoft Word format

There are at least three ways to create a template:

1. The Word document creates support phrases, for example, "[Different Point]", then, in the processing module, search and replacing values.

2. The Word document creates bookmarks to which you can then apply by name. The minus of this method is that the label must be unique, i.e., if you need to insert the surname of the employee in each text paragraph, you will have to make several bookmarks with different names.

3. The Word document adds service fields, such as "Docvariable" or "Author". Using Docvariable can be referred to a variable named, for example, "Dochemstructions .Variables.add (permissive, mean-reflected);", but it is not visible in the template. The "Author" field is displayed in the template, but it will be necessary to access it in the index cycle: "Documers.fields.Item (index) .Result.Text \u003d value;".

In my opinion, the first method is the most optimal. The document template is easily edited, the support phrases are visible in the text. Therefore, the template is creating this way.

Open microsoft program Office. For example, add a couple of lines, as shown in the figure below and save the template.

Creating an external printed form "Treaty"

We run 1C: Enterprise in the "Configurator" mode and through the "File" menu - "new" create external processing. We add the "Link to the object" props and the "Auto Registration Settings" layout with the Tabular Document type. The type of Requisite "Link to the object" depends on what objects the printed form will be used, in our case, the printed form will use for the document "Implementation of goods and services" for the document, so we indicate the type "Document roll.Realizations of the service".

Print procedure development

Currently, we work with Lord of Fear over one interesting project - we develop a solution based on the 1C platform: Enterprise 8.2 for one large company. For the tasks, 1c opportunities are more than abuse and we do not regret our choice. Actually, it will be not about the Great and Mighty Platform 1C: Enterprise.

One of key functions Our program is generating printed forms of various legislative documents (protocols, notifications, etc.). FROM technical side It seems that everything is simple - create a standard layout of the type of table document and begic to its layout. We spent time and quickly threw all the printed forms. It turned out well, but then the customer demanded to redo the design, and we sat down in a puddle. The problem was impossible to apply formatting styles to certain words inside one cell. Yes, you can apply the style to a whole cell, but this method did not come up, because In one cell there may be a few words, and somehow only one of them was especially allocated.

In principle, this problem can be solved by reducing the size of the cellular document cells. In certain cases, with such (small) cells, it is easier to work, but too often change such a markup of the buzz too. Anyway for me.

We thought we thought and decided to abandon typical layouts of the type "tabular document", and the abuse of MS Word. The idea was about this:

1. Create templates of necessary documents. All template files were created precisely as templates for MS Word. Who is not aware, templates are files with DOT extension. On their basis, you can create new documents.

2. Using OLE technology, create documents and replace pseudo-variables to the desired text. Pseudo-variables were drawn up in the form: [name permit].

3. Depending on the situation, print or save the formed document.

There are no difficulties in principle, but before that day we did not have to work from "1C: Enterprise" with MS Word. Basically, all the layouts created by me are based on tabular documentsTherefore, experience in data transfer from the platform, let's say in MS Word / Excel I did not have. The reading of data from Excel had to do frequently, but to transmit - never.

Having performed a couple of tracks under the guitar, we decided to postpone the long-suffering tool and proceed to work. A little couch and reading the helpe, we were sketched here such a faithful:

// Create a new object type Word.Application WordApplication \u003d New Com object ("Word.Application"); // Create a new document based on the template // In the variable path, specify the full path to the created // by the template (file with the DOT extension) of the 2ndocument \u003d WordApplication .documents.add (Pathchaslum); // Preparing for the search for replacementContament \u003d New Document.conent.find; // Replace the text // in the first parameter of the EXECUTE method, we transmit a string that you want to replace // in the ninth - line to which it will be replaced //. In fact, we will transmit the name of the variable (for example, [username]) // and in the latter - its value of replacement of office .execute (that, lie, lie, truth, lies, truth, lie, line (odd)); // Further all depends on our Wishlifts // Saving a document New Document.Saveas (Passion); // Printing a document New Document.Printout (); // Upon completion, you need to close the document and WINWORD itself. This is done so // for the QUIT method I transmit the value of the lie. This suggests that we do not need to save the completed document. Wordapplication.application.quit (lie); WordApplication \u003d 0;

Results of work

The use of MS Word to generate elegant printed forms has fully arranged. We spent a couple of hours for writing procedures, as well as converted previously created forms under MS Word templates. We remained the result than satisfied. Everything works smartly and our customer without problems can independently change the templates of output documents. In case of jambs (well, if the customer randomly drops the existing templates), we provided the ability to restore the original template files.

If you decide to apply these approach in your projects, then be careful. The use of all these nisas requires MS Word on a computer. Given that today many companies go to the terrible (IMHO) OpenOffice - application this method May cause difficulties. Fortunately, we were lucky in this regard.

ATTENTION! When using the codes described below, remove the character. _
Let's look at the examples as it is done! \u003d) I know 2 ways:
1. By replacing the template text in the Word layout.
2. By inserting text using bookmarks in Word,

In the first case, I will immediately say that the length of the string is transmitted to the replacement function, rather small 255 characters, and the arrangement of template expressions in the Word layout takes quite a long time. Through the CONTENT.FIND.EXECUTE procedure.

In the second case, the length, as far as I know unlimited, also to eat with the bookmarks is much faster and more convenient than to expose the template text. Using Bookmarks (). S_Elect (). Therefore, let's look at the second example on the code.

And so, first need to add Word layout to the document. Add a layout using the layout constructor, specifying Active Document and selecting the appropriate layout.

Call his act. Open the layout in 1 list, we put the cursor in the right place, go to the Insert tab. Clicking Add Bookmark For example, I have a disruptivete

Now we throw the button on the form of the document and write a code that opens our Word layout looking for a bookmark by name and inserts text:
Code 1C V 8.x // Initialization Part 1
Link Macket \u003d Receive (Act);
MSWORD \u003d Script pack. Pour ();
Attempt
Link-scale \u003d msword.application.documents (1);
Script pack.ActiveVate ();
// Unload table part With violations in a string Part 2
STR \u003d new COMBACK (ADODB.Stream);
str.open ();
Stritch \u003d elementforms. Independents. Ticked;
For each row of cycle
str.WriteText (+ Strachtakes. Description + Violated Requirements SnowdropsGost: + Strachtakes. Snipflage + Article: + Strachtakes. Pastaty + Symbol (13), 0);
EndCycle;
str.position \u003d 0;
Impairment \u003d str.ReadText ();

// Insert the text to the tab with disorders part 3
Msword.bookmarks (disruptive) .s_elect ();
Msword.application.s_election.typetext (disruptivete);

Script pack.ActiveVate ();
An exception
// If the error
Report (Description ());
Msword.application.quit ();
Celebrations;
This is an example of withdrawing a plurality of lines from a table part with one line, if you just need to unload some kind of props, then you can skip part 2 and go to part 3.

To unload the tabular part in the form of a table, you can use the auto-format function, the example of the unloading code of the table part of the document prescription:
Code 1C V 8.x Word \u003d msword.application;
Document \u003d Word.ActiveDocument ();
// Move down by 22 lines
Word.s_election.movedown (, 22);
Document.paragraphs.add ();
// Table preparation:
RNG \u003d Word.s_election.Range;
// We form a title:
RNG.I_NSERTAfter (No. P / P * Installed disorders and measures to eliminate * base);
RNG.I_NSERTPARAGRAPHAfter ();
// Table itself
Stritch \u003d elementforms. Individuality. Type. Ticked;
For each line of violations of the cycle
RNG.I_NSERTAfter (string (line) + * + * + row.Description +; + Stritch. Duty + * + Stritch. Snipflage + + Strachtakes. Pastaty);
RNG.I_NSERTPARAGRAPHAfter ();
EndCycle;
RNG.ConvertTotable (*);
Document.Tables (1) .Autoformat (17); // Table number in the template
Word.visible \u003d truth;
Well, that's all \u003d)

More way to Active Document
In the configurator layouts - Right click - Add
Layout type: Active Document
Create a new one - Microsoft Word Document

Insert Menu - Field - Automation - DocVariable
Write the name of the field in the column "New Name:" Data Raz

We create a button in the form module, and write it in its handler:



Komobject.Variables.Item ("DataPrice"). Value \u003d "01/24/2007";
Komobject.fields.update ();

KOMOBEKT.PRINTOUT (); // Print Document

// Waiting for the end of sending to print ...
While Objword.application.BackGroundPrintingStatus.<>0 cycle
Warning ("Waiting", 1);
EndCycle;

Komobject.application.quit (); // Close Word.
Combine \u003d 0;
Extrudresses

2) add not the field, but a bookmark
Insert menu - Bookmark and then specify its name ("Issue")
Code 1C V 8.s Procedure Basic FormsFord (Button)
Actual document \u003d receiving ("layout");
Komobject \u003d Actual Document. Pour ();
Komobject.application.visible \u003d 1;
Komobject.Bookmarks (Sokrlp ("Issue")). S_Elect ();
Komobject.application.s_election.typetext (SokrLP ("Test Check"));
Extrudresses

Code 1C V 8.2 UP // The parameters of the contract are indicated in the text of the variables of the form "[% of the number-operator%]"
Print Focument () Export Function

Treaty \u003d Receive ("ActiveDocument_dog Publishing"); // Get Layout-ActiveDocument
MSWORD \u003d contract. Pour ();
Attempt
Doc \u003d msword.application.documents (1);
Doc.activate ();
Replace \u003d doc.content.find;

FindText \u003d "(DOCTOR)"; // What to search - the name of the list
Matchcase \u003d false; // Use regular expressions
Matchwholeword \u003d truth; // Search the word entirely
Matchwildcards \u003d false; // Embed regular expressions
MatchSoundsLike \u003d undefined; // Search for consonant
MATCHALLWORDFORMS \u003d undefined; // look for all forms of the word
Forward \u003d truth; // Search for ahead
Wrap \u003d undefined; // What Must Return the Find Object
Format_ \u003d false; // Use formatting
ReplaceWith \u003d "N777"; // Text you want to replace the name list

// briefly:
//Replace.Execute (FindText is typical of the record is the record);

Replace.Execute (
FindText,
Matchcase,
Matchwholeword,
Matchwildcards,
MatchSoundsLike,
MatchallwordForms,
Forward,
Wrap,
Format_,
Contract number);

Msword.application.visible \u003d truth;
Msword.activate ();
An exception
Report (Description ());
Msword.application.quit ();
Celebrations;

Return 0;

Publication - yours Reating a memo containing code examples for:

1. Filling the template Word Danis out of 1c;
2. Filling footers Word. data from 1C;
3. Filling a table in WORD data from 1C;

Beginning of work

In most cases, we are faced with the following task:
Need to open document Word.filled with 1C data.

To do this, we need to prepare Word document template. Do not confuse it with Word Template, special files Word that contain documents settings for repeated use. We need an ordinary Vordvian document with the extension * .docx or * .doc. And then place this document on the layout with binary data.

Attempt // Get a layout of binary data pattern \u003d reception (optional parameters. Viddogan); NameFile \u003d Optional Equareno File (". Docx"); Template. recording (name); // Create a COM object to work with Word object \u003d new COM object ("Word.Application"); Objects.documents.add (Name File); // In Word, you can open several documents in one application, so objects.application.documents is a collection of open documents. // In our case, the document is always open one documents \u003d objects.application.documents (1); Docterns.ActiveVate (); Exception to report ("Error starting an application" + Description ()); Celebrations; // Of course, getting a COM object must be placed in an attempt. Little, something will go wrong.

The reader can rightly notice that a modal call is used, and to pursue the author with a finger. And will be right.

// Create the structure of the parameters of the parameters of the document flow \u003d prepare the CutterParameters (); // Fill the structure of the parameters of the document of fill-strueges (parameters);

Divide a little bit in the principles of Word ...

Each Word document is divided into partitions that consist of pages.

For each section, it is possible to create your numbering of elements, unique footers and page parameter settings. So, for example, to rotate one of the pages (to print as landscape), you need to create a separate section under it.

Each word page divided into several areas:

  • Page header
  • Main text
  • footer

It should be noted that in each section there may be a unique footer for the first page.

// Object contains all the main text from all partitions documents.content // The object contains a collection of document documenic groups .sections // In each section, there is a collection for the upper footers of dockeners.sections (1) .headers // and its own collection for the lower Handers of documemaker.sections (1) .footers // At the same time, if it is a tick "Unique footer for the first page", then the collections of Headers and Footers will contain two elements

Filling user parameters

When contacting these collections, we can search them and receive built-in objects, such as tables.

Now we are more or less understood how to access the Word regions, we can joke in them and replace our parameters:

// After you by moving all the parameters and replace them in the document for each parameter from the Operation Cycle parameter (Dochemtent.Content, parameter. Butt, parameter. // Looking for the occurrence of the parameter in the upper footer after execution (documemakers.sections (1) .Headers.Item (1) .range (), parameter. Welcome, parameter. // Looking for the entry of the parameter in the footer of the first and subsequent page to execute (dochemstructions.sections (1) .footers.Item (1) .range (), parameter. Welcome, parameter. Relationship); Execution (dochemers.sections (1) .footers.Item (2 )range (), parameter. Turn, parameter. EndCycle; // Perform and replace the execution function (object Object, parameter, value) object.find.execute (parameter, value, 2) endfunction

Consider more EXECUTE Method. Its parameters are identical to the dialogue window when replacing / searching the restarted MS Word:

And here are the main parameters (free transfer of MSDN reference):

  1. The desired text is a string - text for replacement. Text may contain special parameters. For example, ^ p - paragraph, ^ T - tabulation
  2. Sensitivity to register - Booleo - if truth, then the search will be carried out with regard to the register
  3. Words entirely - Boolean - if the truth, then we are looking for words entirely. The entry of words is not taken into account. For example, when searching for the word, the word home will be missed
  4. Use wildcard signs - Booleo - if truth, then built-in regular expressions are used.
  5. Search for similar - Buleovo - If Truth, the search result will contain similar words
  6. Search all forms - Boolean - if truth, the search result will contain various forms of words.
  7. Search at first - Boolevo - if the truth, then will be carried out from the beginning to the end of the document
  8. Coverage - WDFindWrap - Defines the search direction
  9. Format - Format - Format of the desired text
  10. Row of replacement - string - a string to which the source text will be replaced
  11. Number of replacements - WDRePlace - Determines how many times to replace
  12. etc.

WDREPLACE - Constant Value:
wdreplaceall 2.
WDReplacenone 0.
WDReplaceOne 1.

This method does not allow you to get a "replacement string" as a dedicated area, but it works somewhere 10 times slower. To obtain a selected area, you can use a slightly adjusted typical function:

// Control Unsword CLAnt with minor changes for configuration UPP 1.3 Function execution (Object value, parameter, value) strfice \u003d "[" + parameter + "]"; Stringasames \u003d string (value); // It is necessary to highlight the areas in which we replace Object.Select (); // Get the selected selection \u003d object.application.selection area; // Find all the entry of the parameter and replace it with the value of the value FindObject \u003d selection.find; FindObject.clearFormatting (); While FindObject.Execute (strificament) cycle If you are saturast (string passage), then selection.delete (); Otherwise Selection.TypeText (str Rocksames); Ended; EndCycle; // cancel selection.collapse (); Endfunction

Already obtained a selected area, you can edit the style of text, font, etc.

// Editing selection.font font // Edit color selection.highlightcolorindex

There is also a second approach using such word objectlike fields. I don't really like it, because In large documents, about 100 pages, these fields begin to bite (disappear, not to substitute the necessary values) and other nonsense. Well, at least in Word 2007. But I will give it anyway:

When preparing a template into a document body, you need to order fields with the DocVariable type (you can insert with hot keys Ctrl + F9).

Access to such fields can be obtained next unchivery:

Docterns.Variables.Item (Game parametrat) .Values

Filling tables on the template

So, we filled out the parameters in the main text of the document, replaced parameters in footers, but we still have one trouble - you need to fill the table.

The approach described below is suitable only for tables with a pre-known format. Those. We can somehow format the table and its lines initially. But then change pretty problematic.

You can access the tables through the document area.

// We access the first table in the main text table \u003d documents.content.Tables (1)

To set the formatting easier in the template, create a table with an empty first line, which we are subsequently deleted.

// Data for filling parameters \u003d parameter documentation. Printing; // Need to leave the header and the first line untouched iterator \u003d 2; Table \u003d Doccuser.Conent.Tables (3); For each row from the parameters, the cycle // by default adds a string above the first table.Rews.add (); Filling strokes (table, iterator, string, "pp, nomenclature, edifractions, price", parameters); Iterator \u003d iterator + 1; EndCycle; // Template structure Contains the name of the columns and their order procedure. Flowstocks (Table, Constitution, Tablement, Designation, Structures, Tablement) Massive \u003d Output. Iterator \u003d 1; For each string from the massive cycle, if the tables are met. Skumps. Init (string) \u003d undefined and string<> "PP" then iterator \u003d iterator + 1; Proceed; // Do not forget that the hat is also a string, and at the numbering we need to exclude it, the line \u003d "PP" then table.cell (settings, iterator) .range (). Text \u003d string (numbering-1); Iterator \u003d iterator + 1; Proceed; Ended; Table.cell (settings, iterator) .range (). Text \u003d Row (Quality Option [Line]); Iterator \u003d iterator + 1; EndCycle; Extrudresses

That's basically it. The main questions arising from Word, I tried to highlight. I hope this review will help you in work \u003d)

Thanks for the advice and comments:
,

Criticism is just welcome. The more comments, the better the guide \u003d)

Very helpful external treatment For all sample configurations 1C: Enterprise 8.3, allows you to form word file By the selected template from the reference books and document documents. With it, you can print out of 1C various specifications, employment contracts and contracts with counterparties, warranty coupons and other things. Having a Word under the hand of the desired structure and slightly improving it, you will get the opportunity to form it directly out of 1C with filling out all the necessary parameters.

Processing principle Next:

  • choose Word the desired structure,
  • in those places of the file where you need to insert information from 1C, make bookmarks,
  • after preparing the template, add it to 1C (file directory),
  • customize the filling of the print template in 1C,
  • we print the necessary documents / directories by selecting the created template.

Preparation of Word Template

To demonstrate processing operation, we will configure the printing of the specifications to the contract from the document the implementation of goods and services. Suppose we have such Word:

From it we will form a full-fledged specification. We start with the fact that insert bookmarks in those places where information needs to be substituted:



In the name of the bookmarks you can not use spaces.

When printing, we will also fill the product table. So that it formed beautifully, leave the cap and one empty string:


We save Word, close.

Setting up template filling

Now in the program, open a log of sales documents, go to the print menu and click the button to configure the print on Word template:


Setting up templates is available only to users with full rights.

In the settings window that opens, the first thing will be created new file. in the program (meaning an element of the reference book Files) And we will learn our Word to it:


In the window that opens, choose to add a file:


Then choose it in the template settings. After that, the bookmark table is filled in, we need to select sources of data filling in these bookmarks:


The source uses the details of the sales document itself, as well as derivatives from these details:

When printing, you can also use additional details of reference books and documents.

The list of available details is very large, it is convenient to use the rapid input:


As a result of the source selection, the table will take the following form:


For the value to the table rows, deposit on cases, as well as the reduction of the name:


To print a table in Word, choose the source table of the document:


After selecting the table, a certificate appears with the names of those details that can be used to display the table in Word. It remains for us to list the necessary props through the comma (in order of the file columns). It is allowed to leave an empty value in the column or write there arbitrary text:


Everything is OK, now we can print the desired Word.

Printing on a configured template is now available for all, i.e. Users do not need to configure print independently.



We can print both one document and list:


On the form of print settings, in addition to creating new templates, you can edit available:


In the event that several Word templates are configured for the object, then when you select the print command, a window opens with a choice of desired:


To avoid conflicts with user access rights to the directory Files You need to install in addition to the processing of the print in Word, the extension for 1C (is in one processing archive), which will provide users with access to reading a reference book.

If you have questions / comments / suggestions for this processing, I will be glad to answer.

Release 1.1.2.2 dated 12/15/2018

To display the date when the template is selected, the ability to select a format has been added, in the table part, in addition to the nomenclature, it is now possible to specify the article and a unit of measurement:


Now you can delete unnecessary patterns:


Release 1.1.2.3 dated January 29, 2019

There was an opportunity to display part of the date separately - day, month (number or name) and year:


For individuals (and counterparties with the physical type), you can now display passport details:


Release 1.1.2.4 dated 03/12/2019

When printing in Word, the table part of the schedule documents appeared the opportunity to use not only the details of this tabular part, but also any details of the nomenclature:


Release 1.1.2.5 dated 07/12/2019

It appeared possible not only to form word template, but also automatically attach it to the source object (in the attached files). To do this, select the setting option. Save to attached files.


At the end of the printing procedure, the form of the attached file will open.


From this form, you can open when you need to view / edit the filled Word template.