.NET

Reply
*Expert Elite*
norman.yuan
Posts: 946
Registered: ‎04-27-2009
Message 1 of 19 (1,593 Views)
Accepted Solution

How to set media (papaer) name when plotting to PDF/DWF

1593 Views, 18 Replies
09-05-2012 02:33 PM

I am building a tool to plot layout content of drawing to PDF/DWF file. The issue I have is that the required output paper size is not a standard paper size (i.e. the paper size does not exists in paper list when the "DWG To PDF.pc3" is selected.

 

In order to plot programmatically, we have to create a PlotSettingsValidator and call

 

PlotSettingsValidator.SetPlotConfigurationName(plotSettings, plotDeviceName, mediaName)

 

For the 3 required arguments:

 

plotSettings: it is copied from current Layout

plotDeviceNameL it will be "DWG To PDF.pc3"

mediaName: ? this is the one I could not decide, because with the available paper list there isn't one that matches the paper size required by the layout.

 

When doing plot to PDF manually in AutoCAD, user would get prompted for using the selected device (PDF.pc3)'s default paper or use a cutom paper size. If choosing to use custom paper size, AutoCAD add a custom paper size into PDF.pc3 in memory. Here is what I could not find: the corresponding API of adding custom paper size to PDF/DWF pc3 device to match required layout paper size.

 

All the PDF plotting samples I can find online (such as Kean's posts on plotting) use a know paper size when SetPlotConfigurationName() is called, thus, not helpful.

 

Does anyone have clue on this?

 

Distinguished Contributor
khoa.ho
Posts: 149
Registered: ‎09-15-2011
Message 2 of 19 (1,575 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

09-05-2012 03:30 PM in reply to: norman.yuan

I had the same problem, still don't know the best way to get the universal media (paper) name. You may create a new enum for media names based on layout paper sizes (a switch case can do that). This new enum is targeted for AutoCAD PDF/DWF virtual printers.

 

Because the paper names are different for each printer type. For example AutoCAD DWF6 ePlot.pc3 and DWG To PDF.pc3 use "ANSI B (11.00 x 17.00 Inches)" for 11x17 paper size, while HP printer uses just "11x17". So the media (paper) name is not unique to pass to the code as it's different from the printer name.

 

My code practice is to pick a partial printer name (as a network printer name is too long) and a partial paper name (as the paper name may be different for each printer type). Then write code to get FULL names of printer and paper.

 

public static string PlotToDevice(ObjectId spaceId, PlotInput plotInput)
{
	...
	// Get full printer name and paper name
	plotInput.PlotDeviceName = GetFullPrinterName(plotInput.PlotDeviceName);
	plotInput.MediaName = GetFullPaperName(plotInput.PlotDeviceName, plotInput.MediaName);
	...
}

/// <summary>
/// Get full name of a printer
/// </summary>
/// <param name="printerName">partial name of the printer</param>
/// <returns></returns>
private static string GetFullPrinterName(string printerName)
{
	foreach (string printer in PrinterSettings.InstalledPrinters)
	{
		if (printer.Contains(printerName))
			return printer;
	}
	return printerName;
}

/// <summary>
/// Get full name of a paper name that belongs to a printer name
/// </summary>
/// <param name="printerName">partial name of the printer</param>
/// <param name="paperName">partial name of the paper</param>
/// <returns></returns>
private static string GetFullPaperName(string printerName, string paperName)
{
	try
	{
		var printer = new PrinterSettings { PrinterName = GetFullPrinterName(printerName) };
		foreach (PaperSize size in printer.PaperSizes)
		{
			if (size.PaperName.Contains(paperName))
				return size.PaperName;
		}
		return printer.DefaultPageSettings.PaperSize.PaperName;
	}
	catch
	{
		return paperName;
	}
}

 

-Khoa

Valued Mentor
fieldguy
Posts: 366
Registered: ‎03-31-2005
Message 3 of 19 (1,537 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

09-06-2012 02:54 PM in reply to: norman.yuan

There was a discussion here and autodesk replied that the addition of custom page sizes was not exposed in the API (scroll to the last post >>here<<.)

 

My workaround was to copy the OOTB pc3 to a name and location of my choice.  Add 1 custom page and move/rename the resulting PMP file to the same location.  You then have to attach your new PMP file to the new PC3 file.  Then you have to add all custom page sizes required.  But, the path does not have to be exposed to the user or acad which means they *probably* won't find it and use/change it (if that's what you want).  You could probably add hidden or read only attributes if necessary - I have not tried that. 

 

Using this method would allow you to create an MSI and include your custom PC3/PMP setup.  I have not got this to work to a physical printer.  But, using OOTB PDF or DWF pc3 files works like a charm. 

ADN Support Specialist
Balaji_Ram
Posts: 660
Registered: ‎03-21-2011
Message 4 of 19 (1,489 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

09-26-2012 06:59 AM in reply to: norman.yuan

This may not be exactly what you are looking for since we do not have the API for adding the custom paper sizes. But here is a blog post on choosing the closest media size from the list of sizes in the PC3 file.

 

http://adndevblog.typepad.com/autocad/2012/05/how-to-implement-plotsettingsvalidatorsetclosestmedian...

 

Hope this is of some help.



Balaji
Developer Technical Services
Autodesk Developer Network

Mentor
SENL1362
Posts: 150
Registered: ‎07-20-2011
Message 5 of 19 (1,480 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

09-27-2012 12:41 AM in reply to: norman.yuan

Hi Norman,

Sorry for the delayed reaction. You might try the next sample, it can define a custom format when special conditions are met

 

	//Tests the following scenario:
		// theLayout is configured: Plot To PDF, sized custom media 7A4 (== w=7X210, h=297)
		// when changing to another device, the media 7A4 must be added to that device(pc3), as the "previous media size"
		// it appeares to work only when the new device is a PC3 device AND
		//    it already contains a media sized larger than the "previous media size", like 2500x841
		// We can make a PC3 file for a printer, change \\printserver\printername into printername.pc3, 
		//    however you cannot attach a PMP file to the PC3 file.
		// The PMP file contains the non standard media size (among other settings) and thus this will work only for
		// already defined PC3 devices with PMP files and one custom media size larger than the required media size.   
        [CommandMethod("Plt")]
        public void PlotWithPlotStyle()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            //string psetupPathname = @"C:\Apldata\AutoCAD\AcadConfig_INFRA\Menu\psetup-PDF.dwg";
            //string plotStyleName = "4Z-PDF";
            string printerName = "TDS600_Beta.pc3";

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {

                db.TileMode = false;
                ed.SwitchToPaperSpace();

                LayoutManager layMgr = LayoutManager.Current;
                Layout theLayout = (Layout)layMgr.GetLayoutId(layMgr.CurrentLayout).GetObject(OpenMode.ForWrite);
                PlotSettingsValidator psVal = Autodesk.AutoCAD.DatabaseServices.PlotSettingsValidator.Current;
                PlotSettings plotSet = new PlotSettings(theLayout.ModelType);
                plotSet.CopyFrom(theLayout);
                //psVal.SetPlotConfigurationName(plotSet, printerName, null);

                PlotConfigManager.SetCurrentConfig(printerName);
                PlotConfigManager.RefreshList(RefreshCode.All);
                PlotConfig tds = PlotConfigManager.CurrentConfig;
                string plotFile = null;
                if (tds.PlotToFileCapability == PlotToFileCapability.PlotToFileAllowed)
                {
                    tds.IsPlotToFile = true;
                    plotFile = Path.Combine(Path.GetDirectoryName(Application.DocumentManager.MdiActiveDocument.Database.Filename), Path.GetFileNameWithoutExtension(Application.DocumentManager.MdiActiveDocument.Database.Filename));
                    plotFile = plotFile + tds.DefaultFileExtension;
                    if (File.Exists(plotFile))
                        File.Delete(plotFile);

                }

                //the next lines will fail because the required PMP file will get referenced by the PC3 
                //string pc3Dir = @"C:\Documents and Settings\avb\Application Data\Autodesk\AutoCAD 2012 - English\R18.2\enu\Plotters";
                //printerName = printerName + ".pc3";
                //tds.SaveToPC3(Path.Combine(pc3Dir, printerName ));
                //PlotConfigManager.SetCurrentConfig(printerName);
                //PlotConfigManager.RefreshList(RefreshCode.All);
                //tds = PlotConfigManager.CurrentConfig;

                //psVal.RefreshLists(plotSet);
                //try
                //{
                //    psVal.SetClosestMediaName(plotSet, plotSet.PlotPaperSize[0], plotSet.PlotPaperSize[1], PlotPaperUnit.Millimeters, true);
                //}
                //catch ( Autodesk.AutoCAD.Runtime.Exception exx ) 
                //{
                //    ed.WriteMessage("\n" + exx.ToString());
                //}

                psVal.SetPlotPaperUnits(plotSet, PlotPaperUnit.Millimeters);

                //theLayout.CopyFrom(plotSet);
                ed.Regen();


                PlotInfo plotInfo = new PlotInfo();
                plotInfo.Layout = theLayout.ObjectId;
                plotInfo.OverrideSettings = plotSet;
                plotInfo.DeviceOverride = tds;

                PlotInfoValidator validator = new PlotInfoValidator();
                //int itIs = validator.IsCustomPossible(plotInfo);
                validator.MediaMatchingPolicy = Autodesk.AutoCAD.PlottingServices.MatchingPolicy.MatchEnabledCustom;
                int itIs = validator.IsCustomPossible(plotInfo);
                validator.Validate(plotInfo);


                //for now see the results
                if (plotInfo.IsValidated && itIs == 0)
                {
                    PlotSettings newNamedPlotStyle = new PlotSettings(theLayout.ModelType);
                    newNamedPlotStyle.CopyFrom(plotInfo.ValidatedSettings);
                    theLayout.CopyFrom(newNamedPlotStyle);

                    newNamedPlotStyle.PlotSettingsName = "7A4-TDS600";
                    psVal.RefreshLists(newNamedPlotStyle);
                    newNamedPlotStyle.AddToPlotSettingsDictionary(db);
                    tr.AddNewlyCreatedDBObject(newNamedPlotStyle, true);
                    psVal.RefreshLists(newNamedPlotStyle);

                    ed.Regen();
                    tr.Commit();
                    return;
                }
                PlotEngine plotEngine = PlotFactory.CreatePublishEngine();
                //None (initial) -> plot -> document -> page -> graphics
                try
                {
                    plotEngine.BeginPlot(null, null);
                    if (tds.IsPlotToFile)
                        plotEngine.BeginDocument(plotInfo, Application.DocumentManager.MdiActiveDocument.Database.Filename, null, 1, true, plotFile);
                    else
                        plotEngine.BeginDocument(plotInfo, Application.DocumentManager.MdiActiveDocument.Database.Filename, null, 1, false, null);

                    PlotPageInfo pageInfo = new PlotPageInfo();
                    ed.WriteMessage("\nPlotting {0} Entities, {1} ", pageInfo.EntityCount, pageInfo.RasterCount);
                    plotEngine.BeginPage(pageInfo, plotInfo, true, null);
                    plotEngine.BeginGenerateGraphics(null);
                    plotEngine.EndGenerateGraphics(null);
                    plotEngine.EndPage(null);
                    plotEngine.EndDocument(null);
                    plotEngine.EndPlot(null);
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage(ex.Message);
                }
                plotEngine.Destroy();

                tr.Commit();
            }
        }

 

*Expert Elite*
norman.yuan
Posts: 946
Registered: ‎04-27-2009
Message 6 of 19 (1,461 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

09-27-2012 06:57 AM in reply to: SENL1362

Thanks for your code. I'll try it out when I can spare some time later and let you know the outcome.

*Expert Elite*
norman.yuan
Posts: 946
Registered: ‎04-27-2009
Message 7 of 19 (1,432 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

10-02-2012 06:52 AM in reply to: SENL1362

Thank you very much SENL 1362, the PlotInfo.IsCustomPossible() is the key to solve my problem, which I had overlooked.

 

This method, looks like, when called, will try to create a custom paper size to match the layout size, if there is not matching paper size defined with the given plotter (in my case, it is "DWG To PDF.pc3"). I guess it is what exactly when we manually to plot to PDF with DWG To PDF.pc3: if there is not matching paper size, AutoCAD prompts you to use different size of paper, or use "previous size". When latter is select, if you click "Properties" button beside the plotter list, you could see a custom paper size is added to the *.pc3's custom paper list. I think this is what PlotInfo.IsCustomPossible() does.

 

A bit of unfortunate, this method does not make into managed development references of ObjectARX SDK documentation. We need to dig into C++ ARX references in the documentation to find out a bit more information on this method.

 

Anyway, now I updated my project with added call to this method, "DWG To PDF.pc3" now can automatically match a paper size to our odd layout size. So, I do not have manually add a custom paper size to the pc3 file and deploy it with my project.

 

Well, even calling IsCutomPossible() method, it is still possible a matched custom paper size cannot be created for various reasons. So, one should try to test the returned value of IsCustomPossible(), which is an Enum type (it is int type in .NET API).

 

Thank agian.

Mentor
SENL1362
Posts: 150
Registered: ‎07-20-2011
Message 8 of 19 (1,426 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

10-02-2012 08:19 AM in reply to: norman.yuan

Youre welcome and thank you for helping me with various LINQ samples.

 

May i tip you on itextSharp tools which make it possible to customize the exported PDF.

For example because Autodesk exports layers (thanks Autodesk) we are now able to turn watermarks on and off based on the workflow status of these drawings. And because we also password protect these PDF's there is no way someone else can change the status. 

 

 

New Member
b612
Posts: 2
Registered: ‎04-16-2013
Message 9 of 19 (1,067 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

04-30-2013 03:17 AM in reply to: norman.yuan

Hi Norman, i'm beginner and I would like to use your code for my layouts, but I don't understand what code you do C # C + + and realize you have a DLL to send it to Autocad? Thanx

Valued Contributor
GrzesiekGP
Posts: 67
Registered: ‎02-03-2012
Message 10 of 19 (1,031 Views)

Re: How to set media (papaer) name when plotting to PDF/DWF

05-02-2013 01:47 AM in reply to: norman.yuan

Anyone fixed this problem?


I also want to setup custom paper size for PDF export, depend on paper size from my real printer (Oce TDS320).

 

I even want to add my paper size for PDF printer, but I can do it only with DWG To PDF.pc3 which (in my opinion) printing text so bad. Adobe PDF is printing better (or any other printer), but I can't define custom papers ...

You are not logged in.

Log into access your profile, ask and answer questions, share ideas and more. Haven't signed up yet? Register

Announcements
Are you familiar with the Autodesk Expert Elites? The Expert Elite program is made up of customers that help other customers by sharing knowledge and exemplifying an engaging style of collaboration. To learn more, please visit our Expert Elite website.

Need installation help?

Start with some of our most frequented solutions to get help installing your software.

Ask the Community